SpringCloud Consul service registration and discovery

Consul achieves strong consistency through the Raft protocol, and distributes health checks through the Agent, which can reduce the heartbeat detection pressure on the server.

Compared with the centralized heartbeat detection mechanism of Eureka Server and the use of P2P replication mode, data consistency cannot be guaranteed, and it has more advantages.

Consul is written in Go language, you need to download the version from Consul official website  https://www.consul.io/downloads .

Here, the consul version is the latest version 1.9.4, and the SpringCloud version is 2.4.4, using multi-module engineering.

1. Unzip, switch to the consul.exe file directory, and use the command to start,

consul agent -dev

The default client access interface is 8500, enter http://localhost:8500 in the browser to open the main interface.

2. Write a log service and register with the Consul registry,

First add maven dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Then add a comment on the startup class:

@EnableDiscoveryClient

In the configuration file:

server:
  port: 8801
spring:
  application:
    name: logservice
  cloud:
    consul:
      host: localhost
      discovery:
        service-name: logservice

Develop an API interface:

@RestController
public class LogServiceController {

    @GetMapping("/log")
    public String log() {
        return "logservice";
    }
}

3. Start the log service

4. Similarly, develop an order service and start

5. Observe the Consul management page, http://localhost:8500/ui/dc1/services

 

6. Introduce Feign in the order service and call the log service.

maven add feignclient dependency

<!--feign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

Add a comment to the startup class:

@EnableFeignClients

Write FeignClient interface:

@FeignClient("logservice")
public interface LogServiceClient {

    @GetMapping("/log")
    String log();

}

Write API interface,

@RestController
public class OrderController {

    @Resource
    private LogServiceClient logServiceClient;

    @GetMapping("order")
    public String order() {
        return logServiceClient.log();
    }

}

7. Test http://localhost:8802/order and output the logservice string.

Guess you like

Origin blog.csdn.net/suoyx/article/details/115014194