最近公司有个项目需要使用搭建一套新的微服务的框架, 原来公司有一套基于SpringBoot的自研项目, 用起来还挺顺手, 只是和公司的框架耦合太多, 所以决定是用SpringCloud来重新整一套. 看了网上很多的例子, 大部分是基于原生的Eureka+Config, 感觉有点重, 正好自己公司一直使用consul来做服务发现和配置中心, 决定使用consul来替换Eureka+Config, 将过程写下来避免后面的同学踩坑.
maven依赖
现在最新的SpringCloud版本为2.0.1.RELEASE, 为了减少踩坑使用了1.5.16.RELEASE版本
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com.xxx</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.16.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-spring-legacy</artifactId>
<version>1.0.3</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
服务注册
集成consul-discover后, 微服务在启动后会将自己注册到consul上, 服务注册的参数提现在bootstrap.yml中, 详见配置:
其中服务名为spring.application.name=demo, 在服务器启动后会自动注册, 关闭时自动清除
spring:
sleuth:
sampler:
#链路采集率, 默认为10%
percentage: 0.1
zipkin:
#zipkin地址
base-url: http://localhost:9411
cloud:
consul:
host: localhost
port: 8500
discovery:
#服务健康检查url
healthCheckPath: /health
#服务健康检查频率
healthCheckInterval: 15s
instance-id: ${spring.application.name}-${server.port}
tags: ${tag}
prefer-ip-address: true
config:
format: yaml
enabled: true
data-key: data
prefix: config
name: ${spring.application.name}/${tag}
application:
name: demo
feign:
hystrix:
enabled: true
demo:
ribbon:
#访问策略
NFLoadBalancerRuleClassName: com.xxx.rule.TagRoundRobinRule
logging:
path: /tmp
level: info
服务配置
服务配置的部分在spring.cloud.consul.config下面属性配置中, 例子中的配置为/config/demo/dev/data下面, 在代码中指定一个类来关联这个属性, 并且可以直接获取属性的变化通知(更改配置后立即生效)
配置为:
test:
property:
value: 800
对应的类为:
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "test.property")
public class UserInfo {
private String value;//要与consul上面一致
private double doubleValue = 1.0d;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
}
需要注意的是, 在启动类上需要加上@EnableConfigurationProperties({UserInfo.class}) 配置才能使绑定生效
Tag支持
在SpringCloud中, 默认环境配置为profile的方式, 即区分了线上, 测试和开发等环境
, 配置中心也以 {applicationName,dev}这种方式来配置, 在demo中我使用了tags的方式, 只能说是一种workaround的方式, 具体是在启动参数中 -Dservice.port=8080 -Dtag=dev 这种方式启动, 从而从配置文件可以根据启动参数来读取配置, 这样的方式最大的优点是灵活, 不依赖于配置打包(很庆幸在bootstrap.yml的spring.cloud.consul.config.name支持斜杆的方式来表示层级, 不然编码成本会很大)
有了tag的配置支持, 那服务发现该怎么做呢? 需要自己添加一个tag支持的RibbonRule
, 通过对tags的筛选达到筛选tag的目的
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.consul.discovery.ConsulServer;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* 基于tag的轮询算法, 增加了对tag的支持, tag可以从配置中读取
*/
public class TagRoundRobinRule extends AbstractLoadBalancerRule {
private static Logger log = LoggerFactory.getLogger(TagRoundRobinRule.class);
@Value("${spring.cloud.consul.discovery.tags}")
private String selfTag;
@Autowired
private Environment env;
private Map<String, String> serverTagMap = new ConcurrentHashMap<>();
private AtomicInteger nextServerCyclicCounter;
public TagRoundRobinRule() {
nextServerCyclicCounter = new AtomicInteger(0);
}
public TagRoundRobinRule(ILoadBalancer lb) {
this();
setLoadBalancer(lb);
}
private List<Server> filterTag(List<Server> list) {
if (CollectionUtils.isEmpty(list)) {
return new ArrayList<>();
}
String appName = ((list.get(0))).getMetaInfo().getAppName();
String cacheTag = serverTagMap.get(appName);
if (StringUtils.isEmpty(cacheTag)) {
String configTag = env.getProperty("service." + appName + ".tag");
cacheTag = StringUtils.isEmpty(configTag) ? selfTag : configTag;
serverTagMap.put(appName, cacheTag);
}
final String tag = cacheTag;
return list.stream().filter(server1 -> {
if (server1 instanceof ConsulServer) {
if (((ConsulServer) server1).getMetadata()
.containsKey(tag)) {
return true;
}
}
return false;
}).collect(Collectors.toList());
}
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
List<Server> reachableServers = filterTag(lb.getReachableServers());
List<Server> allServers = filterTag(lb.getAllServers());
int upCount = reachableServers.size();
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
int nextServerIndex = incrementAndGetModulo(serverCount);
server = allServers.get(nextServerIndex);
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
/**
* Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
*
* @param modulo The modulo to bound the value of the counter.
* @return The next value.
*/
private int incrementAndGetModulo(int modulo) {
for (; ; ) {
int current = nextServerCyclicCounter.get();
int next = (current + 1) % modulo;
if (nextServerCyclicCounter.compareAndSet(current, next)) {
return next;
}
}
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}