2017-07-25 124 views
1

我打算創建一個微服務應用程序,並提供處理數據的專用服務(主要是基於Mongodb的服務)。我想知道是否有一種方法可以讓我的其他微服務能夠與此服務通信以利用共享數據。 JHipster API網關有可能嗎? 如果不是我怎麼能做到這一點。我不想在每個微服務中保留相同數據的多個副本。微服務如何可以與JHipster中的其他微服務對話

+0

微服務之間的依賴關係應儘可能避免,它只會讓您的整體解決方案變得更慢更弱,這可能表明您的域邊界是錯誤的(請參閱DDD)。您的問題缺乏詳細信息,但網關將JWT令牌傳遞給可將其轉發給其他服務的服務 –

+0

不要執行專用數據存儲。每個MS應該有自己的持久性。 –

回答

1

您可以將所有微服務註冊到相同的註冊表,然後他們可以互相調用。

UPDATE:這是我如何使它工作。 在微服務消費的數據之一,使用RestTemplate與當前用戶JWT令牌授權的頭,使API調用:使用ClientHttpRequestInterceptor在頭部添加標記

@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。

@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); 

     } 

} 
+0

救命!我一直試圖弄清楚這幾個星期了... –

+0

不客氣! – freemanpolys

0

典型的微服務相互交談。這就是整個問題。在發現Eureka的情況下,您只需通過名稱而不是通常在沒有微服務的情況下使用的FQDN來調用微服務。

例如,您book-service將調用author-service這樣 http://author-service/authors

這裏充分例如https://spring.io/blog/2015/01/20/microservice-registration-and-discovery-with-spring-cloud-and-netflix-s-eureka

請不要忘記,JHipster是基於關春雲的自以爲是的框架,這樣你就可以通過搜索春天文檔發現大多數的這些東西。