Consul Service Discovery

Consul is an open source service registry discovery tool developed in Go language that supports distributed, highly available service discovery and configuration sharing in multiple data centers, widely used in large-scale distributed systems.

Spring Cloud natively supports service registration discovery using Consul, similar to Eureka and ZooKeeper.

Download Consul software, run Consul agent-dev on it, and start development mode

Add dependencies to your project

compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')Copy the code

Add Consul Registration center configuration

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500Copy the code

Open http://localhost:8500 to view the service registration status

Service Provider Indicates the service provider

Port 5030 provides a set of interfaces for managing user information:

    @PostMapping("/user")
    User addUser(@RequestBody User user);

    @GetMapping("/getauser")
    User getUser(@RequestParam("id") Integer id);

    @GetMapping("/user")
    List<User> getAllUser(a);

    @DeleteMapping("/user")
    void deleteUser(@RequestParam("id") Integer id);Copy the code

Configuring the MySQL Database

spring.datasource.dbcp2.driver-class-name=com.mysql.jdbc.Driver Spring. The datasource. Url = JDBC: mysql: / / 127.0.0.1:3306 / userdb? useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=qqqq
spring.jpa.hibernate.ddl-auto=updateCopy the code

Service consumer

Here feign is used to invoke the service provider and then provide the user information related interface on port 5031

    @PostMapping("/user/add/{name}")
    User addUser(@PathVariable("name") String name);

    @GetMapping("/user/{id}")
    User getUser(@PathVariable("id") Integer id);

    @GetMapping("/user")
    List<User> getUserList(a);Copy the code

Perform a post request to http://localhost:5031/user/add/Lerry add a data to the database

Is obtained by http://localhost:5031/user user list

[{"id": 1."name": "Lerry"."img": "http://up.qqjia.com/z/16/tu17317_45.png"."sex": "girl"."age": 20."time": 1499761984675
    },
    {
        "id": 4."name": "kity"."img": "http://up.qqjia.com/z/16/tu17317_45.png"."sex": "girl"."age": 20."time": 1499762171942}]Copy the code

Project source code:spring-cloud-consul

Check out my wechat public account