这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战
快速开始一个EurekeServer服务
我们还是在我们原先的项目创建一个新的模块 eurek_server
添加我们SpringCloud的依赖,这里要注意的是,我们不同版本的SpringBoot版本,需要对应相应的SpringCloud版本,否则就会出现错误,具体相对应的版本我们可以去官网查看
- start.spring.io/actuator/in… 这是使用json方式表达的版本号对应,我们可以按F12更好的去查看版本号
- spring.io/projects/sp… 通过我们SpringCloud版本找到相应的SpringBoot版本
我使用的是SpringBoot2.5.7和SpringCloud3.0.2
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>3.0.2</version>
</dependency>
接下来再去编写一下我们的配置文件
server:
port: 9000
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false #是否将自己注册到注册中心
fetch-registry: false #是否从注册中心获取信息
#配置暴露给注册中心的请求地址
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
这些添加完成之后,我们需要在我们的启动类上添加@EnableEurekaServer
注解,这个注解是用来激活我们的注册中心配置的。
在浏览器上输入我们刚刚配置的网址,就能看到如下页面,就说我们的注册中心成功了
将服务注册到我们的注册中心中
我们在我们需要被注册的模块中,进行配置
eureka:
client:
service-url:
defaultZone: http://localhost:9000/eureka/
instance:
prefer-ip-address: true
我们上面的的路径就是我们注册中心刚刚配置的路径
之后在我们的启动类中添加@EnableDiscoveryClient
标签先启动注册中心,在启动我们的被注册服务就可以了
进入我们刚刚的页面
我们就能看到我们刚刚模块被注册到注册中心中
通过注册中心去调用服务
要想调用我们注册中心的服务,那也要添加注册中心相关依赖,添加ymal配置
之后就可以编写Controller层代码了
注入DiscoveryClient对象,要注意我们的DiscoveryClient来自
import org.springframework.cloud.client.discovery.DiscoveryClient;
这个路径下的,不要导错包
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
public Product findById(@PathVariable int id){
//以调用服务名称获取所有的元数据
List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PRODUCT");
for (ServiceInstance instance : instances) {
System.out.println(instance);
}
//获取唯一一个元数据
ServiceInstance serviceInstance = instances.get(0);
//根据元数据中的主机地址和端口号拼接请求微服务的URL
Product forObject = restTemplate.getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/product/1", Product.class);
return forObject;
}
[EurekaServiceInstance@4de16c02 instance = InstanceInfo [instanceId = LAPTOP-VC6VLIE3:service-product:9001, appName = SERVICE-PRODUCT, hostName = 192.168.2.3, status = UP, ipAddr = 192.168.2.3, port = 9001, securePort = 443, dataCenterInfo = com.netflix.appinfo.MyDataCenterInfo@309a4a33]
这是我们输出数据信息,我们可以了利用这些信息,来拼接我们URL,来减少我们的耦合度