一、构建消费端
1.1 定义消费接口(feign客户端)
@Component
//Feign客户端
@FeignClient("spring-cloud-consul-producer")
public interface ConsumerFeignClient {
@GetMapping("/helloConsul")
public String getConsulHello();
}
1.2 在控制器中使用
@RestController
public class ConsumerHelloController {
@Autowired
private ConsumerFeignClient consumerFeignClient;
@GetMapping("/consumer/hello")
public String consumerHello() {
return consumerFeignClient.getConsulHello();
}
}
1.3 消费端也注册到consul
cloud:
consul:
host: localhost
port: 8500
discovery:
tags: dev
serviceName: spring-cloud-consul-producer
healthCheckPath: /actuator/health
healthCheckInterval: 15s
healthCheckUrl: http://127.0.0.1:8080/actuator/health
register: true
1.4 在pom.xml中加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
二、启动consul
C:myinforjavaproj>consul agent -dev
==> Starting Consul agent...
Version: 'v1.7.4'
Node ID: '2de2c666-48d6-9656-ca7e-52f94e16f043'
Node name: 'LAPTOP-22U0U9OO'
Datacenter: 'dc1' (Segment: '<all>')
Server: true (Bootstrap: false)
Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, gRPC: 8502, DNS: 8600)
Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false, Auto-Encrypt-TLS: false
==> Log data will now stream in as it occurs:
三、启动两个服务提供者和上面得消费者
![1667065263b20dc9d6c7e37461604030.png](https://i-blog.csdnimg.cn/blog_migrate/ccbd7d8bea7bfb56f3d4c3f7a1682ce0.png)
![6145df17a5d84b773e155c67fc00dd71.png](https://i-blog.csdnimg.cn/blog_migrate/de762ca69666e71c0efa3264aae2e691.png)
四、消费端默认通过轮询得负载策略访问服务提供者
![c7981520438ec61fda7ad3babefdc7d1.png](https://i-blog.csdnimg.cn/blog_migrate/378695c7bf6e8fe6e619c8bbe0349aaf.png)
![3ad6234081830b1d35bd36352465cdef.png](https://i-blog.csdnimg.cn/blog_migrate/d76ff08b64ed68b92d5ab9dcef8b956a.png)