Skip to content

Commit 10dd0ac

Browse files
committed
Looking up service instances with Spring DiscoveryClient
1 parent 877c37f commit 10dd0ac

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.cevher.ms.person.config;
2+
3+
import com.cevher.ms.person.vm.DepartmentVM;
4+
import lombok.RequiredArgsConstructor;
5+
import lombok.extern.slf4j.Slf4j;
6+
import lombok.val;
7+
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.cloud.client.ServiceInstance;
9+
import org.springframework.cloud.client.discovery.DiscoveryClient;
10+
import org.springframework.http.HttpMethod;
11+
import org.springframework.http.ResponseEntity;
12+
import org.springframework.stereotype.Component;
13+
import org.springframework.web.client.RestTemplate;
14+
15+
import java.util.List;
16+
17+
/**
18+
* Looking up service instances with Spring DiscoveryClient. The Spring DiscoveryClient offers
19+
* the lowest level of access to Ribbon and the services registered within it. Using the DiscoveryClient,
20+
* you can query for all the services registered with the ribbon client and their corresponding URLs.
21+
* Next, you’ll build a simple example of using the DiscoveryClient to retrieve one of
22+
* the organization service URLs from Ribbon and then call the service using a standard RestTemplate class.
23+
*/
24+
@Component
25+
@RequiredArgsConstructor
26+
@Slf4j
27+
public class DepartmentDiscoveryClient {
28+
29+
private final DiscoveryClient discoveryClient;
30+
31+
public DepartmentVM getDepartment(String departmentId) {
32+
RestTemplate restTemplate = new RestTemplate();
33+
List<ServiceInstance> instances = discoveryClient.getInstances("department-service");
34+
35+
if (instances.size() == 0) return null;
36+
String serviceUri = String.format("%s/v1/departments/%s", instances.get(0).getUri().toString(), departmentId);
37+
log.info("!!!! SERVICE URI: " + serviceUri);
38+
39+
val restExchange = restTemplate.exchange(
40+
serviceUri,
41+
HttpMethod.GET,
42+
null,
43+
DepartmentVM.class,
44+
departmentId);
45+
46+
return restExchange.getBody();
47+
}
48+
}

0 commit comments

Comments
 (0)