本文主要是介绍SpringCloud:服务保护——通过Future机制自定义服务保护,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一,上一篇通过Hystrix对服务保护进行了分析;这一篇基于Future,分版本由浅入深对服务降级和服务隔离机制进行说明
二,服务端代码,线程随机沉睡200MS以内,客户端调用100MS超时,制造可能超时场景
package com.gupao.member.service.impl;import com.gupao.api.service.IMemberServier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author pj_zhang* @create 2019-01-09 23:48**/
@RestController
public class MemberService implements IMemberServier {@Value("${server.port}")private Integer serverPort;@Override@RequestMapping("/getMember_1")public String getMember_1() throws InterruptedException {int sleepTime = new Random().nextInt(200);System.out.println("getMember_1, thread sleep : " + sleepTime);Thread.sleep(sleepTime);System.out.println("getMember_1 Thread Name : " + Thread.currentThread().getName());return "MemberService.getMember_1, serverPort : " + serverPort;}
}
三,客户端自定义接口处理
1,初级版本——容错实现
* 代码实现
package com.gupao.order.self;import com.gupao.order.feign.IMemberServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.*;/*** @author pj_zhang* @create 2019-01-22 22:55**/
@RestController
public class SelfCircuitBreaker {// 创建一个线程池private final ExecutorService executorService = Executors.newSingleThreadExecutor();@Autowiredprivate IMemberServiceFeign memberServiceFeign;@RequestMapping("/low")public String getMember() {// 通过Callable发起异步线程, 获取回调结果long startTime = System.currentTimeMillis();Future<String> future = executorService.submit(new Callable<String>() {@Overridepublic String call() throws Exception {return memberServiceFeign.getMember_1();}});// future阻塞获取回调结果String returnValue = null;long endTime = 0L;try {returnValue = future.get(100, TimeUnit.MILLISECONDS);} catch (Exception e) {// 报错后取消执行服务future.cancel(true);returnValue = "服务调用超时...";}System.out.println("returnValue : " + returnValue + ", costTime : " + (System.currentTimeMillis() - startTime));return returnValue;}}
* 服务端控制台输出
* 客户端控制台输出
2,中级版本——拦截器实现
* Rest接口
@RequestMapping("/middle")public String middle() throws InterruptedException {return memberServiceFeign.getMember_1();}
* 拦截器实现
package com.gupao.order.interceptor;import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;import javax.annotation.PreDestroy;
import java.util.concurrent.*;/*** @author pj_zhang* @create 2019-01-22 23:11**/
@Aspect
@Component
public class SelfServerInterceptor {private ExecutorService executorService = Executors.newSingleThreadExecutor();@Around("execution(public * com.gupao.order.self.SelfCircuitBreaker.middle(..))")public String getMember(final ProceedingJoinPoint proceedingJoinPoint) {return doServer(proceedingJoinPoint, 100L);}private String doServer(final ProceedingJoinPoint proceedingJoinPoint, Long timeOut) {long startTime = System.currentTimeMillis();// 通过Callable发起异步线程, 获取回调结果Future<String> future = executorService.submit(new Callable<String>() {@Overridepublic String call() throws Exception {try {// 执行目标方法return JSONObject.toJSONString(proceedingJoinPoint.proceed());} catch (Throwable throwable) {return "服务调用失败";}}});// 阻塞等待方法执行完成String returnValue = null;try {returnValue = future.get(100, TimeUnit.MILLISECONDS);} catch (Exception e) {future.cancel(true);returnValue = "服务请求超时...";}System.out.println("returnValue : " + returnValue + ", costTime : " + (System.currentTimeMillis() - startTime));return returnValue;}@PreDestroypublic void destory() {executorService.shutdown();}}
* 运行结果
3,高级版本——拦截器+注解实现
* 添加注解
package com.gupao.order.annotation;import java.lang.annotation.*;/*** @author pj_zhang* @create 2019-01-22 23:24**/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CircuitBreakder {long outTime() default 100;
}
* 服务调用接口
@RequestMapping("/high")@CircuitBreakder(outTime = 100L)public String high() throws InterruptedException {return memberServiceFeign.getMember_1();}
* 拦截器实现
@Around("execution(public * com.gupao.order.self.SelfCircuitBreaker.high(..))")public String getMemberByHigh(final ProceedingJoinPoint proceedingJoinPoint) {// 通过注解获取超时时间long outTime = 100L;if (proceedingJoinPoint instanceof MethodInvocationProceedingJoinPoint) {MethodInvocationProceedingJoinPoint methodPoint = (MethodInvocationProceedingJoinPoint) proceedingJoinPoint;MethodSignature signature = (MethodSignature) methodPoint.getSignature();Method method = signature.getMethod();CircuitBreakder circuitBreaker = method.getAnnotation(CircuitBreakder.class);outTime = circuitBreaker.outTime();}return doServer(proceedingJoinPoint, outTime);}
* 运行结果
4,通过信号灯实现单机版限流方案
* 注意暂时去掉Feign客户端的Hystrix服务保护,此处在原项目上实现,受超时时间影响
@FeignClient(name = "app-itmayiedu-member")
public interface IMemberServiceFeign extends IMemberServier {
}
* Hystrix超时时间默认1S,进行修改
###服务启动端口号
server:port: 8100
###服务名称(服务注册到eureka名称)
spring:application:name: app-itmayiedu-order
###服务注册到eureka地址
eureka:client:service-url:defaultZone: http://localhost:8000/eureka###因为该应用为注册中心,不会注册自己register-with-eureka: true###是否需要从eureka上获取注册信息fetch-registry: true
###设置feign客户端超时时间
ribbon:
###指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间。ReadTimeout: 50000
###指的是建立连接后从服务器读取到可用资源所用的时间。ConnectTimeout: 50000### 开启hystrix断路器
feign:hystrix:enabled: true### hystrix超时时间
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds : 100000
* 修改服务端睡眠时间,睡眠5S
@Override@RequestMapping("/getMember_1")public String getMember_1() throws InterruptedException {Thread.sleep(5000);System.out.println("getMember_1 Thread Name : " + Thread.currentThread().getName());return "MemberService.getMember_1, serverPort : " + serverPort;}
* 自定义注解添加限流属性
package com.gupao.order.annotation;import java.lang.annotation.*;/*** @author pj_zhang* @create 2019-01-22 23:24**/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CircuitBreakder {long outTime() default 100;int value() default 5;
}
* 定义REST接口
@RequestMapping("/limit")public String limit() throws InterruptedException {return memberServiceFeign.getMember_1();}
* 拦截器实现
@Around("execution(public * com.gupao.order.self.SelfCircuitBreaker.limit(..))")public String limit(final ProceedingJoinPoint proceedingJoinPoint) {// 通过注解获取超时时间Integer limitValue = 5;if (proceedingJoinPoint instanceof MethodInvocationProceedingJoinPoint) {MethodInvocationProceedingJoinPoint methodPoint = (MethodInvocationProceedingJoinPoint) proceedingJoinPoint;MethodSignature signature = (MethodSignature) methodPoint.getSignature();Method method = signature.getMethod();CircuitBreakder circuitBreaker = method.getAnnotation(CircuitBreakder.class);limitValue = circuitBreaker.value();}// 初始化信号量if (semaphore == null) {semaphore = new Semaphore(limitValue);}String returnValue = null;try {// 获取到可用信号, 执行方法if (semaphore.tryAcquire()) {returnValue = JSONObject.toJSONString(proceedingJoinPoint.proceed());// 未获取到可用信号, 返回错误提示} else {returnValue = "Semaphore 限流...";}} catch (Throwable throwable) {returnValue = "执行异常";} finally {semaphore.release();}System.out.println("returnValue : " + returnValue);return returnValue;}
* 频繁刷新页面数次,直到刷新出预期结果
这篇关于SpringCloud:服务保护——通过Future机制自定义服务保护的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!