服务治理介绍
先来思考一个问题
通过上一章的操作,我们已经可以实现微服务之间的调用。但是我们把服务提供者的网络地址(ip,端口)等硬编码到了代码中,这种做法存在许多问题:
一旦服务提供者地址变化,就需要手工修改代码
一旦是多个服务提供者,无法实现负载均衡功能
一旦服务变得越来越多,人工维护调用关系困难
那么应该怎么解决呢, 这时候就需要通过注册中心动态的实现服务治理。
什么是服务治理
服务治理是微服务架构中最核心最基本的模块。用于实现各个微服务的自动化注册与发现
服务注册: 在服务治理框架中,都会构建一个注册中心,每个服务单元向注册中心登记自己提供服
务的详细信息。并在注册中心形成一张服务的清单,服务注册中心需要以心跳的方式去监测清单中
的服务是否可用,如果不可用,需要在服务清单中剔除不可用的服务。
服务发现: 服务调用方向服务注册中心咨询服务,并获取所有服务的实例清单,实现对具体服务实例的访问。
服务注册中心,它是微服务架构非常重要的一个组件,在微服务架构里主要起到了协调者的一个作用。注册中心一般包含如下几个功能:
- 服务发现:
服务注册:保存服务提供者和服务调用者的信息
服务订阅:服务调用者订阅服务提供者的信息,注册中心向订阅者推送提供者的信息
- 服务配置:
配置订阅:服务提供者和服务调用者订阅微服务相关的配置
配置下发:主动将配置推送给服务提供者和服务调用者
- 服务健康检测
检测服务提供者的健康情况,如果发现异常,执行服务剔除
常见的注册中心
Zookeeper
zookeeper是一个分布式服务框架,是Apache Hadoop 的一个子项目,它主要是用来解决分布式
应用中经常遇到的一些数据管理问题,如:统一命名服务、状态同步服务、集群管理、分布式应用
配置项的管理等。
Eureka
Eureka是Springcloud Netflix中的重要组件,主要作用就是做服务注册和发现。但是现在已经闭
源
Consul
Consul是基于GO语言开发的开源工具,主要面向分布式,服务化的系统提供服务注册、服务发现
和配置管理的功能。Consul的功能都很实用,其中包括:服务注册/发现、健康检查、Key/Value
存储、多数据中心和分布式一致性保证等特性。Consul本身只是一个二进制的可执行文件,所以
安装和部署都非常简单,只需要从官网下载后,在执行对应的启动脚本即可。
Nacos
Nacos是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。它是 Spring
Cloud Alibaba 组件之一,负责服务注册发现和服务配置,可以这样认为nacos=eureka+config。
nacos简介
Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速
实现动态服务发现、服务配置、服务元数据及流量管理。
从上面的介绍就可以看出,nacos的作用就是一个注册中心,用来管理注册上来的各个微服务。
nacos
搭建nacos环境acos
下载Nacos:https://nacos.io/en-us/
win下启动:\nacos\bin目录下点击startup.cmd启动
访问:http://127.0.0.1:8848/nacos/ 默认账号密码均为:nacos
将商品微服务注册到nacos
接下来开始修改 shop-product 模块的代码, 将其注册到nacos服务上
1、在pom.xml中添加nacos的依赖
<!--nacos客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
yml
server:
port: 8081
spring:
application:
name: user
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.0.2:3306/demo?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
logging:
level:
com.jx.user.dao : debug
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Application
package com.jx.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author yangxinlei
* @date 2020/8/10
*/
@SpringBootApplication
@EnableDiscoveryClient
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class,args);
}
}
order服务同样方式注册到注册中心
服务调用
修改JxOrderServiceImpl
package com.jx.user.service.impl;
import com.alibaba.fastjson.JSON;
import com.jx.common.User;
import com.jx.user.dao.JxOrderMapper;
import com.jx.user.service.JxOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author yangxinlei
* @date 2020/8/11
*/
@Service
@Slf4j
public class JxOrderServiceImpl implements JxOrderService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private JxOrderMapper jxOrderMapper;
@Override
public Object getOrderList() throws Exception {
log.info(">>用户信息");
//从nacos中获取服务地址
ServiceInstance serviceInstance = discoveryClient.getInstances("user").get(0);
String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
log.info(">>从nacos中获取到的微服务地址为:" + url);
//通过restTemplate调用商品微服务
List<User> product = restTemplate.getForObject("http://user/user/getUserList", List.class);
log.info(">>用户信息,查询结果:" + JSON.toJSONString(product));
return product;
}
}
JxOrderApplication
package com.jx.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @author yangxinlei
* @date 2020/8/11
*/
@SpringBootApplication
@EnableDiscoveryClient
public class JxOrderApplication {
public static void main(String[] args) {
SpringApplication.run(JxOrderApplication.class,args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
实现服务调用的负载均衡
什么是负载均衡
通俗的讲, 负载均衡就是将负载(工作任务,访问请求)进行分摊到多个操作单元(服务器,组件)上进行执行。
根据负载均衡发生位置的不同,一般分为服务端负载均衡 和客户端负载均衡 。
服务端负载均衡指的是发生在服务提供者一方,比如常见的nginx负载均衡
而客户端负载均衡指的是发生在服务请求的一方,也就是在发送请求之前已经选好了由哪个实例处理请求。
自定义实现负载均衡
通过idea再启动一个 user 微服务,设置其端口为8083
-Dserver.port=8083
通过nacos查看微服务的启动情况
修改JxOrderServiceImpl
package com.jx.user.service.impl;
import com.alibaba.fastjson.JSON;
import com.jx.common.User;
import com.jx.user.dao.JxOrderMapper;
import com.jx.user.service.JxOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* @author yangxinlei
* @date 2020/8/11
*/
@Service
@Slf4j
public class JxOrderServiceImpl implements JxOrderService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private JxOrderMapper jxOrderMapper;
@Override
public Object getOrderList() throws Exception {
log.info(">>用户信息");
//从nacos中获取服务地址
List<ServiceInstance> instances = discoveryClient.getInstances("user");
int index = new Random().nextInt(instances.size());
ServiceInstance serviceInstance = instances.get(index);
String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
log.info(">>从nacos中获取到的微服务地址为:" + url);
//通过restTemplate调用商品微服务
List<User> product = restTemplate.getForObject("http://user/user/getUserList", List.class);
log.info(">>用户信息,查询结果:" + JSON.toJSONString(product));
return product;
}
}
基于Ribbon实现负载均衡
Ribbon是Spring Cloud的一个组件, 它可以让我们使用一个注解就能轻松的搞定负载均衡
在RestTemplate 的生成方法上添加@LoadBalanced注解
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
修改服务调用
package com.jx.user.service.impl;
import com.alibaba.fastjson.JSON;
import com.jx.common.User;
import com.jx.user.dao.JxOrderMapper;
import com.jx.user.service.JxOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* @author yangxinlei
* @date 2020/8/11
*/
@Service
@Slf4j
public class JxOrderServiceImpl implements JxOrderService {
@Autowired
private RestTemplate restTemplate;
@Override
public Object getOrderList() throws Exception {
log.info(">>用户信息");
//直接使用微服务名字, 从nacos中获取服务地址
String url = "user";
//通过restTemplate调用商品微服务
List<User> product = restTemplate.getForObject("http://"+url+"/user/getUserList", List.class);
log.info(">>用户信息,查询结果:" + JSON.toJSONString(product));
return product;
}
}
策略名 | 策略描述 | 实现说明 |
---|---|---|
BestAvailableRule | 选择一个最小的并发 请求的server | 逐个考察Server,如果Server被tripped了,则忽略,在选择其中ActiveRequestsCount最小的server |
AvailabilityFilteringRule | 过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(activeconnections 超过配置的阈值) | 使用一个AvailabilityPredicate来包含过滤server的逻辑,其实就就是检查status里记录的各个server的运行状态 |
WeightedResponseTimeRule | 根据相应时间分配一个weight,相应时间越长,weight越小,被选中的可能性越低。 | 一个后台线程定期的从status里面读取评价响应时间,为每个server计算一个weight。Weight的计算也比较简单responsetime 减去每个server自己平均的responsetime是server的权重。当刚开始运行,没有形成statas时,使用roubine策略选择server。 |
RetryRule | 对选定的负载均衡策略机上重试机制。 | 在一个配置时间段内当选择server不成功,则一直尝试使用subRule的方式选择一个可用的server |
RoundRobinRule | 轮询方式轮询选择server | 轮询index,选择index对应位置的server |
RandomRule | 随机选择一个server | 在index上随机,选择index对应位置的server |
ZoneAvoidanceRule | 复合判断server所在区域的性能和server的可用性选择server | 使用ZoneAvoidancePredicate和AvailabilityPredicate来判断是否选择某个server,前一个判断判定一个zone的运行性能是否可用,剔除不可用的zone(的所有server),AvailabilityPredicate用于过滤掉连接数过多的Server。 |
修改application.yml
user: # 调用的提供者的名称
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
基于Feign实现服务调用
加入Fegin的依赖
<!--fegin组件-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
JxOrderApplication
package com.jx.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @author yangxinlei
* @date 2020/8/11
*/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients//开启Fegin
public class JxOrderApplication {
public static void main(String[] args) {
SpringApplication.run(JxOrderApplication.class,args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
新建一个service
package com.jx.user.service;
import com.jx.common.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/**
* @author yangxinlei
* @date 2020/8/12
*/
@FeignClient("user")
public interface UserService {
@GetMapping(value = "/user/getUserList")
Object userGetUserList();
}
调用
@Autowired
private UserService userService;
Object product = userService.userGetUserList();
log.info(">>用户信息,查询结果:" + product);