版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ErErFei/article/details/79075717
微服务可以在“自己的程序”中运行,并通过“轻量级设备与HTTP型API进行沟通”。这里的
沟通
就是本节要说的服务间通讯。即各个微服务注册到Eureka服务注册中心,这些微服务之间的通讯
创建服务提供者
启动上一节 Eureka入门——集群的服务内容,把hello-service作为服务提供者,通过java -jar hello.jar --server.port=8181
和java -jar hello.jar --server.port=8282
启动两个hello-service服务,打开Eureka信息面板可以看到两个HELLO-SERVICE实例
创建服务消费者
新建Spring Boot项目MeetSpringCloud
,spring.application.name=ribbon-consumer(别怀疑为什么叫ribbon)在pom.xml中增加ribbon
依赖
<dependency>
<groupid>org.springframework.cloud</groupid>
<artifactid>spring-cloud-starter-ribbon</artifactid>
</dependency>
修改主类MeetSpringCloud.java
如下
@EnableDiscoveryClient
@SpringBootApplication
public class MeetSpringCloudApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(MeetSpringCloudApplication.class, args);
}
}
在包com.centerm.controller
下创建类ConsumerController.java
如下,消费HELLO-SERVICE提供的getIndex服务
@RestController
@RequestMapping("")
public class ConsumerController {
@Autowired
RestTemplate restTemplate;
@GetMapping("ribbon-consumer")
public String helloConsumer() {
return restTemplate.getForEntity("http://HELLO-SERVICE/getIndex",
String.class).getBody();
}
}
修改application.yml如下:
server:
port: 9091
eureka:
client:
serviceUrl:
defaultZone: http://peer1:11111/eureka/,http://peer2:22222/eureka/
spring:
application:
name: ribbon-consumer
运行程序,打开Eureka信息面板
体验消费结果
查看ribbon-consumer的日志可以看到下面的信息,列出了可用服务的列表以及访问状态等信息,有关Ribbon
的详细介绍会在后面的章节中涉及
DynamicServerListLoadBalancer for client HELLO-SERVICE initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=HELLO-SERVICE,current list of Servers=[AGOD21-05021513:8181, AGOD21-05021513:8282],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone; Instance count:2; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
},Server stats: [[Server:AGOD21-05021513:8282; Zone:defaultZone; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
, [Server:AGOD21-05021513:8181; Zone:defaultZone; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@1c0a0a56