spring-boot integrate with consul client

Setup the consul environment

Please refer to below article
https://blog.csdn.net/yaominhua/article/details/82316287

Add dependency to pom.xml

<dependency>
    <groupId>com.orbitz.consul</groupId>
    <artifactId>consul-client</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Register the service when application startup

Create the Consul client bean

@Configuration
public class ConsulConfig {

    @Bean
    public Consul consul() {
        // default host is localhost and defalt port is 8500
        return Consul.newClient();
    }

}

Create application listener

public class ConsulRegisterListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Consul consul = event.getApplicationContext().getBean(Consul.class);
        int port = 8080;
        int interval = 10;
        String serviceName = "helloWorldService";
        List<String> tag = new ArrayList<>();
        Map<String, String> meta = new HashMap<>();
        try {
            consul.agentClient().register(port,
                    URI.create("http://localhost:8080/actuator/health").toURL(),
                    interval,
                    serviceName,
                    serviceName,
                    tag,
                    meta);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

}

Add listener to SpringApplication

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication sa = new SpringApplication(Application.class);
        sa.addListeners(new ConsulRegisterListener());
        sa.run(args);
    }

}

Discover the service

Create a server class to store the available servers

public class Server {

    private String host;
    private int port;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

}

Create the discovery service

@Component
public class ServiceDiscovery {

    @Autowired
    private Consul consul;

    public List<Server> getServerList(String serviceName) {
        List<Server> upServerList = new ArrayList<>();
        List<ServiceHealth> availableServers = consul.healthClient().getHealthyServiceInstances(serviceName).getResponse();
        availableServers.forEach(x -> {
            Server server = new Server();
            server.setHost(x.getNode().getAddress());
            server.setPort(x.getService().getPort());
            upServerList.add(server);
        });
        return upServerList;
    }

}

Create the controller to have a test

@RestController
@RequestMapping("helloWorld")
public class HelloWorldController {

    @Autowired
    private ServiceDiscovery serviceDiscovery;

    @RequestMapping(value="serverList/{serviceName}",method=RequestMethod.GET)
    public List<Server> getServerList(@PathVariable("serviceName") String serviceName) {
        return serviceDiscovery.getServerList("serviceName");
    }

}

Use below url to test the result:
http://localhost:8080/helloWorld/serverList/helloWorldService

猜你喜欢

转载自blog.csdn.net/javalover_yao/article/details/82317368