0
点赞
收藏
分享

微信扫一扫

六、Spring cloud高可用服务治理(Consul)

DYBOY 2022-06-21 阅读 46

一、快速上手

(一)安装
1、下载https://releases.hashicorp.com/consul/1.3.0/consul_1.3.0_linux_386.zip

2、解压之后就直接可以用了

3、检测是否可用
执行以下 ./consul 出现以下信息就说明安装成功

[root@localhost soft]# ./consul
usage: consul [--version] [--help] <command> [<args>]

Available commands are:
agent Runs a Consul agent
configtest Validate config file
event Fire a new event
exec Executes a command on Consul nodes
force-leave Forces a member of the cluster to enter the "left" state
info Provides debugging information for operators
join Tell Consul agent to join cluster
keygen Generates a new encryption key
keyring Manages gossip layer encryption keys
kv Interact with the key-value store
leave Gracefully leaves the Consul cluster and shuts down
lock Execute a command holding a lock
maint Controls node or service maintenance mode
members Lists the members of a Consul cluster
monitor Stream logs from a Consul agent
operator Provides cluster-level tools for Consul operators
reload Triggers the agent to reload configuration files
rtt Estimates network round trip time between nodes
snapshot Saves, restores and inspects snapshots of Consul server state
version Prints the Consul version
watch Watch for changes in Consul

4、开启 Consul 端口8500,以便客户端远程访问

/sbin/iptables -I INPUT -p tcp --dport 8500 -j ACCEPT
/etc/rc.d/init.d/iptables save

(二)Agent
错误启动方法:

#单机启动(经测试,客户端无法远程连接)
./consul agent -dev

正确启动方法:

#启动 Server 端
./consul agent -server -bind=127.0.0.1 -client=0.0.0.0 -bootstrap-expect=1 -data-dir=/tmp/consul_data/ -node=server1 -ui

参数解析:
-server 表示是以服务端身份启动
-bind 表示绑定到哪个ip(有些服务器会绑定多块网卡,可以通过bind参数强制指定绑定的ip)
-client 指定客户端访问的ip(consul有丰富的api接口,这里的客户端指浏览器或调用方),0.0.0.0表示不限客户端ip
-bootstrap-expect=3 表示server集群最低节点数为3,低于这个值将工作不正常(注:类似zookeeper一样,通常集群数为奇数,方便选举,consul采用的是raft算法)(我这里用的是1,是为了测试效果)
-data-dir 表示指定数据的存放目录(该目录必须存在)
-node 表示节点在web ui中显示的名称
-ui 可以通过访问“​​​http://192.168.10.130:8500/ui”,在浏览器里管理​​ Consul

(三)键值存储(KV Store)

./consul kv put key value

(四)UI控制台

./consul agent -dev -ui

二、Spring Cloud 整合

1、引入依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>

2、激活服务发现客户端

/**
* 激活服务发现客户端
*/
@EnableDiscoveryClient
@SpringBootApplication
public class ConsulApplication {

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

3、利用服务发现API操作

(1)配置应用信息

#应用名称
spring.application.name=spring-cloud-consul
#服务端口
server.port=8080

#配置连接 Consul 服务器的配置
##主机地址
spring.cloud.consul.host=192.168.10.130
##Consul 服务端口
spring.cloud.consul.port=8500

#调整 Health Check 路径,使其传递到 Consul 服务器,帮助回调(否则Consul服务器会认为客户端已挂)PS:这里自定义个Controller
#spring.cloud.consul.discovery.health-check-path=/check

management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

(2)编写 DiscoveryClient Contoller

package org.pc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;

/**
* {@link DiscoveryClient}{@link RestController}
* @author 咸鱼
* @date 2018/11/4 10:04
*/
@RestController
public class DiscoveryClientController {
/**
* 在启动类加上{@link @DiscoveryClient}注解以后,DiscoveryClient就会成为一个Bean,
* 可以自动装配进来。
*/
private final DiscoveryClient discoveryClient;

private final String currentServiceInstanceName;

/**
* 注解:@Value("${spring.application.name}"),就是我们在application.properties中
* 配置的应用名(spring.application.name)
*/
@Autowired
public DiscoveryClientController(DiscoveryClient discoveryClient,
@Value("${spring.application.name}")String currentServiceInstanceName) {
this.discoveryClient = discoveryClient;
this.currentServiceInstanceName = currentServiceInstanceName;
}

/**
* 获取所有服务名
*/
@GetMapping("/current")
public ServiceInstance getCurrentServiceInstance(){
return discoveryClient.getInstances(currentServiceInstanceName).get(0);
}
/**
* 获取所有服务名
*/
@GetMapping("/list/services")
public List<String> listServices(){
return discoveryClient.getServices();
}

/**
* 获取所有的服务实例信息
*/
@GetMapping("/list/service-instances")
public List<ServiceInstance> listServiceInstances(){
List<String> services = listServices();
List<ServiceInstance> serviceInstances = new LinkedList<>();
services.forEach(serviceName ->
serviceInstances.addAll(discoveryClient.getInstances(serviceName))
);
return serviceInstances;
}
}


举报

相关推荐

0 条评论