Eureka 客户端服务注册 与 消费
Posted shaoxin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Eureka 客户端服务注册 与 消费相关的知识,希望对你有一定的参考价值。
pom中添加依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>$spring-cloud.version</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
application.yml
#优雅退出配置
management:
endpoint:
shutdown:
enabled: true
endpoints:
web:
exposure:
include:
- shutdown
- info
- health
spring:
application:
name: eureka-provider
server:
port: 9090
#服务注册
eureka:
client:
service-url:
defaultZone: http://eureka:[email protected]:8761/eureka,http://eureka2:8761/eureka
SpringCloudEurekaClientApplication.java 启动类加注解
package com.example.springcloudeurekaclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableEurekaClient @SpringBootApplication public class SpringCloudEurekaClientApplication public static void main(String[] args) SpringApplication.run(SpringCloudEurekaClientApplication.class, args);
消费注册表中服务:
@Autowired private LoadBalancerClient loadBalancerClient; public List<User> getUser() //选择调用服务的名称 ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-provider"); //拼接访问服务的URL StringBuffer sb = new StringBuffer(); sb.append("http://").append(serviceInstance.getHost()).append(":") .append(serviceInstance.getPort()).append("/getUser"); //restTemplate请求模板 RestTemplate restTemplate = new RestTemplate(); ParameterizedTypeReference<List<User>> typeReference = new ParameterizedTypeReference<List<User>>() ; //封裝返回值信息 ResponseEntity<List<User>> responseEntity = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, typeReference); List<User> body = responseEntity.getBody(); return body;
以上是关于Eureka 客户端服务注册 与 消费的主要内容,如果未能解决你的问题,请参考以下文章