思路:通过eureka 注册中心获取其他服务的信息,ip,端口
一,服务消费者引用EurekaClient 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
二,修改服务消费者启动类,激活eurekaClient (可选)
@SpringBootApplication
@EntityScan("com.zjk.order.entity")
@EnableEurekaClient //激活EurekaClient
public class OrderApplication {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
}
三,引用 DiscoveryClient 类 ,这个类是springCloud client 的类
DiscoverClient 类
package org.springframework.cloud.client.discovery;
import java.util.List;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.core.Ordered;
public interface DiscoveryClient extends Ordered {
int DEFAULT_ORDER = 0;
String description();
List<ServiceInstance> getInstances(String serviceId);
List<String> getServices();
default int getOrder() {
return 0;
}
}
四,通过 DiscoveryClient 类,的方法,找到需要调用服务的ip,端口
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping(value = "/findByIds/{Id}")
public TbProduct findByIds(@PathVariable Long Id){
try {
List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
ServiceInstance serviceInstance = instances.get(0);
TbProduct tbProduct = restTemplate.getForEntity("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/product/{Id}", TbProduct.class,Id).getBody();
return tbProduct;
}catch (Exception e){
e.printStackTrace();
}
return null;
}