Home > Archives > 微服务:在Spring Cloud中使用Consul实现服务的注册和发现

微服务:在Spring Cloud中使用Consul实现服务的注册和发现

Publish:

首先安装consul环境,参照之前的文章:《服务注册发现consul之一:consul介绍及安装》中的第一节介绍。

我们配置三个服务器:

consul-server1

package com.baoguoding.consulserver1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ConsulServer1Application {

	@RequestMapping("/home")
	public Object home() {
		System.out.println("cloud-server1");
		return "cloud-server1";
	}

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

}

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
spring.cloud.consul.discovery.healthCheckInterval=15s
spring.cloud.consul.discovery.instance-id=consul-server1
spring.application.name=consul-server
server.port=8503

[
    {
        "ID": "68c9aed5-1bc2-2a9a-7d60-80f8cf87be9c",
        "Node": "baoguo-PC",
        "Address": "127.0.0.1",
        "Datacenter": "dc1",
        "TaggedAddresses": {
            "lan": "127.0.0.1",
            "wan": "127.0.0.1"
        },
        "NodeMeta": {
            "consul-network-segment": ""
        },
        "ServiceKind": "",
        "ServiceID": "consul-server1",
        "ServiceName": "consul-server",
        "ServiceTags": [
            "secure=false"
        ],
        "ServiceAddress": "baoguo-PC",
        "ServiceWeights": {
            "Passing": 1,
            "Warning": 1
        },
        "ServiceMeta": {},
        "ServicePort": 8503,
        "ServiceEnableTagOverride": false,
        "ServiceProxyDestination": "",
        "ServiceProxy": {},
        "ServiceConnect": {},
        "CreateIndex": 12,
        "ModifyIndex": 12
    }
]

consul-server2

参考源代码

consul-client

参考源代码

[
	{
		"instanceId": "consul-server1",
		"serviceId": "consul-server",
		"host": "baoguo-PC",
		"port": 8503,
		"secure": false,
		"metadata": {
			"secure": "false"
		},
		"uri": "http://baoguo-PC:8503",
		"scheme": null
	},
	{
		"instanceId": "consul-server2",
		"serviceId": "consul-server",
		"host": "baoguo-PC",
		"port": 8504,
		"secure": false,
		"metadata": {
			"secure": "false"
		},
		"uri": "http://baoguo-PC:8504",
		"scheme": null
	}
]

参考

声明: 本文采用 BY-NC-SA 授权。转载请注明转自: Ding Bao Guo