Consul 微服务注册与发现

1. 创建Spring Boot项目

IDE :IntelliJ IDEA

File ->new->project->Spring Initializer 创建Spring Boot项目

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.examplegroupId>
    <artifactId>consul_demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>consul_demoname>
    <description>Demo project for Spring Bootdescription>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.8.RELEASEversion>
        <relativePath/> 
    parent>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-websocketartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-starter-loggingartifactId>
                exclusion>
            exclusions>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-log4j2artifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-consul-discoveryartifactId>
            <version>1.2.1.RELEASEversion>
        dependency>

        <dependency>
            <groupId>com.corundumstudio.socketiogroupId>
            <artifactId>netty-socketioartifactId>
            <version>1.7.12version>
        dependency>

        
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.5version>
        dependency>

        
        <dependency>
            <groupId>com.orbitz.consulgroupId>
            <artifactId>consul-clientartifactId>
            <version>0.16.3version>
        dependency>

        
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
            <version>2.8.0version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.37version>
        dependency>

    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>

2. Controller

package com.example.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zxl on 17-10-22.
 */
@RestController
@RequestMapping("/api")
public class HttpController {

    /**
     * 健康检查
     * @return
     */
    @RequestMapping("/healthCheck")
    public Object healthCheck() {
        return "success";
    }

    /**
     * 服务接口
     * @return
     */
    @RequestMapping("/hello")
    @ResponseBody
    public Object service() {
        return "hello";
    }
}

3. application.properties

spring.application.name=consul_demo
server.port=8080
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.enabled=true
spring.cloud.consul.discovery.enabled=true
#spring.cloud.consul.discovery.instanceId=${spring.application.name}
//微服务名称
spring.cloud.consul.discovery.serviceName=consulServiceTest
spring.cloud.consul.discovery.hostname=http://${spring.cloud.consul.host}/api
//健康检查
spring.cloud.consul.discovery.healthCheckUrl=http://${spring.cloud.consul.host}/api/healthCheck
spring.cloud.consul.discovery.healthCheckInterval=10s
spring.cloud.consul.discovery.tags=dev

4. consul启动

进入consul目录执行如下脚本

consul_start.sh

export node=`hostname`
killall -9 consul
./consul agent  -data-dir /software/consul -node=$node -bind=192.xx.xxx.xx(本机Ip)  -join=192.yy.yy.yy(consul Server Ip)

5. 启动程序

执行main方法

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class ConsulDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsulDemoApplication.class, args);
    }
}

6. 服务发现

public class ConsulUtil {

    static Consul consul = Consul.builder().withHostAndPort(
            HostAndPort.fromString(PropertyUtils.getProperty("ConsulServerIp"))).build();

    public static Consul getConsul() {
        return consul;
    }

    public static String getService(String serviceName, String tag) {
        String address = null;
        Consul consul = ConsulUtil.getConsul();
        HealthClient healthClient = consul.healthClient();
        ConsulResponse> allHealthyServiceInstance
                = healthClient.getHealthyServiceInstances(serviceName);
        //获取健康的服务
        List response = allHealthyServiceInstance.getResponse();
        List services = new ArrayList<>(response.size());
        for (ServiceHealth serviceHealth : response) {
            services.add(serviceHealth.getService());
        }
        Random random = new Random();
        if (services.size() == 0) {//无法获取健康的服务
            return null;
        }
        address = services.get(random.nextInt(services.size())).getAddress() + "/" + tag;
        return address;
    }
}

你可能感兴趣的:(JAVA)