Consul is a service grid (TCP/IP between microservices, responsible for network calls, traffic limiting, fuses, and monitoring between services) solution that is a distributed, highly available system that is easy to develop and use. It provides a fully functional control plane, the main features are: service discovery, health check, key value storage, secure service communication, multi-data center

Reference sq.163yun.com/blog/articl…

First, start Consul
Consul – Client
  • Add dependencies to the POM.xml file
<dependency>
    <groupId>com.orbitz.consul</groupId>
    <artifactId>consul-client</artifactId>
    <version>1.36.</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Copy the code
  • Service registration and health check


package daemo.check;


import com.orbitz.consul.*;
import com.orbitz.consul.model.agent.ImmutableRegCheck;
import com.orbitz.consul.model.agent.ImmutableRegistration;
import com.orbitz.consul.model.agent.Registration;
import com.orbitz.consul.model.health.ServiceHealth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;


import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.List;




public class ServiceRegister implements ApplicationListener<ContextRefreshedEvent> {


    private static final Logger logger  = LoggerFactory.getLogger(ServiceRegister.class);


    @Value("${spring.application.name}")
    private String appName;


    Consul client = Consul.builder().build();
    AgentClient agentClient = client.agentClient();


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        logger.info("Start registration");
        try {
            // Health check is used in the actuator, which is configured in application.properties
            //management.endpoints.web.base-path=/monitor
            //management.endpoint.health.show-details=always
            //management.endpoints.web.exposure.include=*
            URL url  = URI.create("http://127.0.0.1:8088/monitor/health").toURL();
            //use server tag
            Registration registration = register("127.0.0.1"."8088",url,3,appName,appName,"devtag");
            agentClient.register(registration);




        }catch (MalformedURLException e) {
            logger.error("You configured a wrong health check URL[{}]! ");
            throw new RuntimeException(e);
        }
    }


    private Registration register(String hostIp, String port, URL http, long interval, String name, String id, String tags) {
        Registration.RegCheck check = ImmutableRegCheck.builder().http(http.toExternalForm()).interval(String.format
                ("%ss".new Object[]{Long.valueOf(interval)})).build();
        ImmutableRegistration.Builder registrationBuilder = ImmutableRegistration.builder().port(Integer.parseInt(port)).check(check).name
                (name).id(id).addTags(tags);
        if (!"localhost".equalsIgnoreCase(hostIp) && !"127.0.0.1".equalsIgnoreCase(hostIp)) {
            registrationBuilder.address(hostIp);
        }
        return registrationBuilder.build();
    }

    /** * Found available services */
    public List<ServiceHealth> findHealthyService(String servicename){
        Consul consul = Consul.builder().build();
        HealthClient healthClient = consul.healthClient();// Access all health services
        return healthClient.getHealthyServiceInstances(servicename).getResponse();// Find the passing node
    }


    /** * store KV */
    public void storeKV(String key, String value){
        Consul consul = Consul.builder().build();
        KeyValueClient kvClient = consul.keyValueClient();
        kvClient.putValue(key, value);/ / store KV
    }


    /** * Get value */ based on key
    public String getKV(String key){
        Consul consul = Consul.builder().build();
        KeyValueClient kvClient = consul.keyValueClient();
        return kvClient.getValueAsString(key).get();
    }


    /** * Find the consistent nodes (should be all server nodes in the same DC) */
    public List<String> findRaftPeers(){
        StatusClient statusClient = Consul.builder().build().statusClient();
        return statusClient.getPeers();
    }


    /** * get leader */
    public String findRaftLeader(){
        StatusClient statusClient = Consul.builder().build().statusClient();
        returnstatusClient.getLeader(); }}Copy the code
  • ConsulConfig configuration
package daemo.config; import daemo.check.ServiceRegister; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @ClasssNmae:ConsulConfig * @Author:sange * @Description: **/ @configuration public class ConsulConfig {@bean public ApplicationListener getEnniuApplicationStartedEvent() { return new ServiceRegister(); }}Copy the code
3. Start the service

View the services registered on the server

【 Actual Combat 】 Consul Cluster Deployment debugging (version 0.7.1)

More exciting public account “51 Operation and Maintenance com”