我计划创建一个微服务应用程序,其中包含一个处理数据的专用服务(主要是基于Mongodb的服务)。我想知道是否有一种方法可以使用我的其他微服务与该服务进行通信以利用共享数据。是否可以使用JHipster API Gateway?如果不是,我怎么能实现这一点。我不想在每个微服务中保留相同数据的多个副本。
您可以将所有微服务注册到同一个注册表,然后他们可以互相调用。
更新:这是我如何使它工作。在使用数据的微服务中,使用RestTemplate与标头中的当前用户jwt令牌授权来进行api调用:
@Component
public class AuthenticateClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
String token = SecurityUtils.getCurrentUserJWT();
httpRequest.getHeaders().add("Authorization","Bearer "+token);
return clientHttpRequestExecution.execute( httpRequest, bytes );
}
}
我的自定义restTemplate使用ClientHttpRequestInterceptor在标头中添加令牌。
@Configuration
public class CustomBean {
@Autowired
AuthenticateClientHttpRequestInterceptor interceptor;
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(interceptor));
return restTemplate;
}
}
在您正在调用数据的资源控制器中:
@RestController
@RequestMapping("/api")
public class DataResource {
@Autowired
RestTemplate restTemplate;
@PostMapping("/hello")
@Timed
public ResponseEntity<Hello> createHello(@RequestBody Hello Hello) throws URISyntaxException {
//The name your data micro service registrated in the Jhipster Registry
String dataServiceName = "data_micro_service";
URI uri = UriComponentsBuilder.fromUriString("//" + dataServiceName + "/api/datas")
.build()
.toUri();
//call the data microservice apis
List<Data> result = restTemplate.getForObject(uri, Data[].class);
return ResponseEntity.created(new URI("/api/hellos/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
}
您也可以使用JHipster的Feign客户端。
用SpringBootApplication
注释你的@EnableFeignClients
...
import org.springframework.cloud.openfeign.EnableFeignClients;
...
@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
@EnableDiscoveryClient
@EnableFeignClients
public class MyApp {
...
}
在您的微服务中创建一个Feign客户端
...
import org.springframework.cloud.openfeign.FeignClient;
...
@FeignClient("another-service")
public interface AnotherClient {
@RequestMapping(method = RequestMethod.GET, value = "/api/another")
List<AnotherDTO> getAll();
}
用@Autowired
注入Feign客户端并调用它。它应该可以使用了。
@RestController
@RequestMapping("/api")
public class MyResource {
...
@Autowired
private AnotherClient anotherClient;
...
@GetMapping("/another")
@Timed
public List<AnotherDTO> getAll() {
log.debug("REST request to get all");
return anotherClient.getAll();
}
}
对我们来说,它没有实现ClientHttpRequestInterceptor
并设置JWT令牌。
通常,微服务相互通信。这就是重点。使用Eureka发现,您只需通过名称而不是我们通常在没有微服务的情况下使用的FQDN来调用微服务。
对于例如你的book-service
将像author-service
一样称为http://author-service/authors
请不要忘记JHipster是一个基于Spring Cloud的固定框架,因此您可以通过搜索Spring文档找到大部分内容。