服务发现:可以使用工具类根据服务名称获取对应的服务地址列表。
实现步骤
- 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 在主类中添加注解,开启Eureka客户端功能
@EnableDiscoveryClient
- 配置application.yml文件
server:
port: 8080
spring:
application: #应用名
name: consumer
eureka:
client:
service-url:
# eureka地址
defaultZone: http://127.0.0.1:10086/eureka
4)编写controller类(这里要注意DiscoveryClient的包,有两个相似的,容易导错,应该是import org.springframework.cloud.client.discovery.DiscoveryClient;)
package com.consumer.consumertest.controller;
import com.consumer.consumertest.pojo.User;
import com.netflix.appinfo.InstanceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@RequestMapping("/con")
public class ConsumerCon {
@Autowired
RestTemplate restTemplate;
@Autowired
DiscoveryClient discoveryClient;
@GetMapping("/{id}")
public User tt(@PathVariable int id) {
String url = "http://localhost:9091/user/" + id;
// 获取eureka中注册的user-service实例列表
List<ServiceInstance> serviceInstancesList = discoveryClient.getInstances("user-service");
ServiceInstance serviceInstance = serviceInstancesList.get(0);
// 动态生成url
url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/" + id;
return restTemplate.getForObject(url, User.class);
}
}