
eureka 启动多个,实现高可用
2,3,4 都向注册中心进行注册,每一个模块都应该使用多个,进行高可用
item和eureka实现高可用
实际情况下,需要在不同主机上进行部署,多台主机,端口号不用修改,但是在一台主机上测试,需要修改端口号
provider高可用配置
8001 端口
java -jar item.jar
java -jar item.jar --server.port=8002
访问两个端口测试
http://localhost:8001/35
http://localhost:8002/35
成功测试界面:
Eureka高可用配置
两个配置
主配置和profile同时存在会运行profile,profile是个性配置,主配置是通用配置
euraka1配置
eureka:
instance:
hostname: eureka1
client:
register-with-eureka: true
fetch-registry: true
euraka2配置
eureka:
instance:
hostname: eureka2
client:
register-with-eureka: true
fetch-registry: true
配置连接地址、
service-url.defaultZone: http://eureka2:2002/eureka
访问测试:
http://eureka1:2001/
http://eureka2:2002/
eureka客户端注册时,向两个服务器注册
修改以下微服务:
sp02-itemservice
sp03-userservice
sp04-orderservice
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
当一个 eureka 服务宕机时,仍可以连接另一个 eureka 服务
测试连接:
06 功能演示项目—远程调用
06 调用02,03,04
02有集群,需要负载均衡调用 Ribbon容错
Ribbon 负载均衡和重试
负载均衡:
远程调用一个服务,在它的集群服务器之间来回调用,分散访问压力
重试:
一种容错方式,当调用远程服务器失败,可以自动进行重试调用
远程调用工具:RestTemplate
Spring 提供的远程调用工具,执行一个HTTP请求,并获得响应,一般获得的是JSON数据
底层有工具API,可将json转化为java对象
对Rest API调用过程做了高度封装,一步就可以完成发送请求,处理响应,json转换
getForObject(url,转化的类型,提交的参数)
postForObject(url,协议体数据,转化的类型)
不是springCloud工具是Spring提供的远程调用工具
Ribbon是对RestTemplate进行了封装,增强了RestTemplate的功能增强
Ribbon 案例测试
增加配置:
<dependency>
<groupId>cn.tedu</groupId>
<artifactId>sp01-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
RestTemplate
-http协议
-一次请求一次响应,之后断开连接,是一种短链接
-直接连接Web(tomcat)服务器
-调用的是Controller
Dubbo
-java序列化
-长连接
-连接Dubbo自己的端口(20880 默认)
-调用Service
-Dubbo效率高
1. 创建实例对象
1 在启动类中配置
2 添加一个配置类
2.创建Controller
package cn.tedu.sp06.controller;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@Slf4j
public class RibbonController {
@Autowired
private RestTemplate rt;
@GetMapping("/item-service/{orderId}")
public JsonResult<List<Item>> getItems(@PathVariable String orderId){
//调用远程服务,调用的是路径
return rt.getForObject("http://localhost:8001/{1}}", JsonResult.class,orderId);
}
}
访问测试:
调用远程的user
@GetMapping("/user-service/{userId}")
public JsonResult<User> getUser(@PathVariable Integer userId){
return rt.getForObject("http://localhost:8101/{1}",
JsonResult.class,userId);
}
@GetMapping("/user-service/{userId}/score")
public JsonResult<?> addScore(@PathVariable Integer userId,Integer score){
return rt.getForObject("http://localhost:8101/{1}/score?score={2}",
JsonResult.class,userId,score);
}
调用远程的订单
@GetMapping("/order-service/")
public JsonResult<?> addOrder(String orderId){
return rt.getForObject("http://localhost:8201/", JsonResult.class);
}
@GetMapping("/order-service/{orderId}")
public JsonResult<Order> getOrder(@PathVariable String orderId){
return rt.getForObject("http://localhost:8201/{1}", JsonResult.class,orderId);
}
启动服务
测试eureka:
http://localhost:3001/user-service/7/score?score=100
http://localhost:3001/order-service/123abc
ribbon 重试
pom.xml 添加 spring-retry 依赖
复制代码到 pom.xml
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
yml
spring:
application:
name: ribbon
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
MaxAutoRetriesNextServer: 2
MaxAutoRetries: 1
OkToRetryOnAllOperations: true
ConnectionTimeout
ReadTimeout
OkToRetryOnAllOperations=true
默认只对GET请求重试, 当设置为true时, 对POST等所有类型请求都重试
MaxAutoRetriesNextServer
更换实例的次数
MaxAutoRetries
当前实例重试次数,尝试失败会更换下一个实例
主程序设置 RestTemplate 的请求工厂的超时属性
package cn.tedu.sp06;
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.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class Sp06RibbonApplication {
@LoadBalanced
@Bean
public RestTemplate getRestTemplate() {
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
f.setConnectTimeout(1000);
f.setReadTimeout(1000);
return new RestTemplate(f);
//RestTemplate 中默认的 Factory 实例中,两个超时属性默认是 -1,
//未启用超时,也不会触发重试
//return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(Sp06RibbonApplication.class, args);
}
}
item-service 的 ItemController 添加延迟代码,以便测试 ribbon 的重试机制
package cn.tedu.sp02.item.controller;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
public class ItemController {
@Autowired
private ItemService itemService;
@Value("${server.port}")
private int port;
@GetMapping("/{orderId}")
public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws Exception {
log.info("server.port="+port+", orderId="+orderId);
///--设置随机延迟
if(Math.random()<0.6) {
long t = new Random().nextInt(5000);
log.info("item-service-"+port+" - 暂停 "+t);
Thread.sleep(t);
}
///~~
List<Item> items = itemService.getItems(orderId);
return JsonResult.ok(items).msg("port="+port);
}
@PostMapping("/decreaseNumber")
public JsonResult decreaseNumber(@RequestBody List<Item> items) {
itemService.decreaseNumbers(items);
return JsonResult.ok();
}
}
访问,测试 ribbon 重试机制
通过 ribbon 访问 item-service,当超时,ribbon 会重试请求集群中其他服务器
http://localhost:3001/item-service/35
ribbon的重试机制,在 feign 和 zuul 中进一步进行了封装,后续可以使用feign或zuul的重试机制
Hystrix 断路器
微服务宕机时,ribbon 无法转发请求
复制 sp06-ribbon 项目,命名为sp07-hystrix
选择 sp06-ribbon 项目,ctrl-c,ctrl-v,复制为sp07-hystrix
关闭 sp06-ribbon 项目,后续测试使用 sp07-hystrix 项目
修改 pom.xml
添加 hystrix 起步依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
修改 application.yml
spring:
application:
name: hystrix
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
MaxAutoRetries: 1
MaxAutoRetriesNextServer: 2
OkToRetryOnAllOperations: true
主程序添加 @EnableCircuitBreaker 启用 hystrix 断路器
启动断路器,断路器提供两个核心功能:
降级,超时、出错、不可到达时,对服务降级,返回错误信息或者是缓存数据
熔断,当服务压力过大,错误比例过多时,熔断所有请求,所有请求直接降级
可以使用 @SpringCloudApplication 注解代替三个注解
package cn.tedu.sp06;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
//@EnableCircuitBreaker
//@EnableDiscoveryClient
//@SpringBootApplication
@SpringCloudApplication
public class Sp06RibbonApplication {
@LoadBalanced
@Bean
public RestTemplate getRestTemplate() {
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
f.setConnectTimeout(1000);
f.setReadTimeout(1000);
return new RestTemplate(f);
//RestTemplate 中默认的 Factory 实例中,两个超时属性默认是 -1,
//未启用超时,也不会触发重试
//return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(Sp06RibbonApplication.class, args);
}
}
RibbonController 中添加降级方法
为每个方法添加降级方法,例如 getItems() 添加降级方法 getItemsFB()
添加 @HystrixCommand 注解,指定降级方法名
package cn.tedu.sp06.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;
@RestController
public class RibbonController {
@Autowired
private RestTemplate rt;
@GetMapping("/item-service/{orderId}")
@HystrixCommand(fallbackMethod = "getItemsFB") //指定降级方法的方法名
public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);
}
@PostMapping("/item-service/decreaseNumber")
@HystrixCommand(fallbackMethod = "decreaseNumberFB")
public JsonResult decreaseNumber(@RequestBody List<Item> items) {
return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
}
/
@GetMapping("/user-service/{userId}")
@HystrixCommand(fallbackMethod = "getUserFB")
public JsonResult<User> getUser(@PathVariable Integer userId) {
return rt.getForObject("http://user-service/{1}", JsonResult.class, userId);
}
@GetMapping("/user-service/{userId}/score")
@HystrixCommand(fallbackMethod = "addScoreFB")
public JsonResult addScore(@PathVariable Integer userId, Integer score) {
return rt.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class, userId, score);
}
/
@GetMapping("/order-service/{orderId}")
@HystrixCommand(fallbackMethod = "getOrderFB")
public JsonResult<Order> getOrder(@PathVariable String orderId) {
return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId);
}
@GetMapping("/order-service")
@HystrixCommand(fallbackMethod = "addOrderFB")
public JsonResult addOrder() {
return rt.getForObject("http://order-service/", JsonResult.class);
}
/
//降级方法的参数和返回值,需要和原始方法一致,方法名任意
public JsonResult<List<Item>> getItemsFB(String orderId) {
return JsonResult.err("获取订单商品列表失败");
}
public JsonResult decreaseNumberFB(List<Item> items) {
return JsonResult.err("更新商品库存失败");
}
public JsonResult<User> getUserFB(Integer userId) {
return JsonResult.err("获取用户信息失败");
}
public JsonResult addScoreFB(Integer userId, Integer score) {
return JsonResult.err("增加用户积分失败");
}
public JsonResult<Order> getOrderFB(String orderId) {
return JsonResult.err("获取订单失败");
}
public JsonResult addOrderFB() {
return JsonResult.err("添加订单失败");
}
}
hystrix 超时设置
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix等待超时后, 会执行降级代码, 快速向客户端返回降级结果, 默认超时时间是1000毫秒
为了测试 hystrix 降级,我们把 hystrix 等待超时设置得非常小(500毫秒)
此设置一般应大于 ribbon 的重试超时时长,例如 10 秒
spring:
application:
name: hystrix
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
MaxAutoRetriesNextServer: 2
MaxAutoRetries: 1
OkToRetryOnAllOperations: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500
启动项目进行测试
通过 hystrix 服务,访问可能超时失败的 item-service
http://localhost:3001/item-service/35
通过 hystrix 服务,访问未启动的 user-service
http://localhost:3001/user-service/7
可以看到,如果 item-service 请求超时,hystrix 会立即执行降级方法
访问 user-service,由于该服务未启动,hystrix也会立即执行降级方法
hystrix dashboard 断路器仪表盘
hystrix 对请求的降级和熔断,可以产生监控信息,hystrix dashboard可以实时的进行监控
sp07-hystrix 项目添加 actuator,并暴露 hystrix 监控端点
actuator 是 spring boot 提供的服务监控工具,提供了各种监控信息的监控端点
management.endpoints.web.exposure.include 配置选项,
可以指定端点名,来暴露监控端点
如果要暴露所有端点,可以用 “*”
pom.xml 添加 actuator 依赖
右键点击项目或pom.xml, 编辑起步依赖, 添加 actuator 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
调整 application.yml 配置,并暴露 hystrix.stream 监控端点
spring:
application:
name: hystrix
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
MaxAutoRetriesNextServer: 1
MaxAutoRetries: 1
OkToRetryOnAllOperations: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500
management:
endpoints:
web:
exposure:
include: hystrix.stream
访问 actuator 路径,查看监控端点
http://localhost:3001/actuator
Hystrix dashboard 仪表盘
新建 sp08-hystrix-dashboard 项目
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.tedu</groupId>
<artifactId>sp08-hystrix-dashboard</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sp08-hystrix-dashboard</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</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>
application.yml
spring:
application:
name: hystrix-dashboard
server:
port: 4001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
hystrix:
dashboard:
proxy-stream-allow-list: localhost
主程序添加 @EnableHystrixDashboard 和 @EnableDiscoveryClient
package cn.tedu.sp08;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@EnableDiscoveryClient
@EnableHystrixDashboard
@SpringBootApplication
public class Sp08HystrixDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(Sp08HystrixDashboardApplication.class, args);
}
}
启动,并访问测试
访问 hystrix dashboard
http://localhost:4001/hystrix
填入 hystrix 的监控端点,开启监控
http://localhost:3001/actuator/hystrix.stream
通过 hystrix 访问服务多次,观察监控信息
http://localhost:3001/item-service/35
http://localhost:3001/user-service/7
http://localhost:3001/user-service/7/score?score=100
http://localhost:3001/order-service/123abc
http://localhost:3001/order-service/