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