博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java B2B2C Springcloud仿淘宝电子商城系统-Hystrix项目中使用
阅读量:6999 次
发布时间:2019-06-27

本文共 11169 字,大约阅读时间需要 37 分钟。

一、公共类、不是必须的

需要JAVA Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码一零三八七七四六二六

package com.xxx.xxx.xxx.data.command.dubbo;import com.netflix.hystrix.*;public abstract class AbstractDubboCommand
extends HystrixCommand
{ /** * @param commandKey */ public AbstractDubboCommand(String commandKey) { super(DubboCommandSetter.setter(commandKey)); } @Override public T getFallback(){ //判断熔断器是否打开 if(super.isCircuitBreakerOpen()){ alert(); } return fallback(); } /** * 当熔断器打开时,报警。报警间隔时间为5分钟 */ public abstract void alert(); /** * 降级处理 * @return */ public abstract T fallback(); public boolean needCache(){ return false; }}复制代码

熔断器的设置

package com.xxx.xxx.xxx.data.command.dubbo;import com.netflix.hystrix.HystrixCommand;import com.netflix.hystrix.HystrixCommand.Setter;import com.netflix.hystrix.HystrixCommandGroupKey;import com.netflix.hystrix.HystrixCommandKey;import com.netflix.hystrix.HystrixCommandProperties;import com.netflix.hystrix.HystrixThreadPoolKey;import com.netflix.hystrix.HystrixThreadPoolProperties;/** * Comand公共参数的设置 * * @author liweihan * @time 2017-12-20 16:53 */public class DubboCommandSetter {    public static Setter setter(String commandKeyName,String threadPoolKeyName) {        return setter("DubboGroup",commandKeyName,threadPoolKeyName);    }    public static Setter setter(String commandKeyName) {        return setter(commandKeyName,"Dubbo-Pool");    }    /**     * @author liweihan     * @time 2017/12/20 16:57     * @description     相关参数设置     * @param groupKeyName      服务分组名     * @param commandKeyName    服务标识名称     * @param threadPoolKeyName 线程池名称     * @return     */    public static Setter setter(String groupKeyName,String commandKeyName,String threadPoolKeyName) {        //服务分组        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(groupKeyName);        //服务标识        HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(commandKeyName);        //线程池名称        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey(threadPoolKeyName);        //线程配置        HystrixThreadPoolProperties.Setter threadPoolProperties = HystrixThreadPoolProperties.Setter()                .withCoreSize(150)                .withKeepAliveTimeMinutes(5)                .withMaxQueueSize(Integer.MAX_VALUE)                .withQueueSizeRejectionThreshold(10000)                ;        //命令属性的配置        HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter()                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)//                .withExecutionIsolationThreadInterruptOnTimeout(true)                .withExecutionTimeoutInMilliseconds(3000) //设置超时时间为3秒进入Fallback                .withCircuitBreakerErrorThresholdPercentage(30)//失败率达到30%自动熔断                .withRequestCacheEnabled(false);        //返回        return HystrixCommand.Setter                .withGroupKey(groupKey)				.andCommandKey(commandKey)                .andThreadPoolKey(threadPoolKey)                .andThreadPoolPropertiesDefaults(threadPoolProperties)                .andCommandPropertiesDefaults(commandProperties);    }}复制代码

获得基础信息-Album的Command类

package com.xxx.xxx.xxx.data.command.dubbo;import com.xxx.xxx.xxx.service.ServiceManager;import com.xxx.xxx.xxx.util.CommonUtil;import com.xxx.xxx.xxx.util.SerializationUtil;import com.xxx.xxx.xxx.util.WxSmsUtils;import com.xxx.xxx.xxx.midware.dubbo.api.dto.AlbumInfoDto;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * @author liweihan * @time 2017/10/12 15:12 * @description 获取PGC/UGC专辑基础信息! */public class GetAlbumInfoByDubboCommand extends AbstractDubboCommand
{ public static final Logger logger = LoggerFactory.getLogger(GetAlbumInfoByDubboCommand.class); Long aid; ServiceManager serviceManager; public GetAlbumInfoByDubboCommand(Long aid , ServiceManager serviceManager) { super("GetAlbumInfo"); this.aid = aid; this.serviceManager=serviceManager; } @Override public AlbumInfoDto fallback() { String key = String.format(CommonUtil.Get_AlbumInfo_ByDubbo, aid); logger.info(" GetAlbumInfoByDubboCommand from dubbo fail,key:{}",key); byte[] obj = serviceManager.getRedisClusterHyStrix().getBytes(key); try { AlbumInfoDto albumInfoDto = (AlbumInfoDto)SerializationUtil.bytes2Object(obj); return albumInfoDto; }catch (Exception e) { logger.error(" ====== GetAlbumInfoByDubboCommand from Hystrix'fallback error,key:{} . Exception:{}" ,key,e); } return null; } @Override protected AlbumInfoDto run() throws Exception { AlbumInfoDto albumInfoDto = null; long beginTime = System.currentTimeMillis(); try { /** * http://mwiki.sohuno.com/pages/viewpage.action?pageId=32866496 */ albumInfoDto = serviceManager.getDubboAlbumService().albumInfo(aid,0,"","17"); } catch (Exception e) { logger.error(" ====== GetAlbumInfoByDubboCommand ,调用dubbo出错!aid:{}",aid,e); } //统计一下该dubbo的访问次数// incr("dubbo_album"); long endTime = System.currentTimeMillis(); if ((endTime - beginTime) > CommonUtil.TIME_OUT_DUBBO) { //统计一下该dubbo超时的访问次数// incr("dubbo_album_timeout"); logger.warn(" ====== GetAlbumInfoByDubboCommand ,调用dubbo时间久!beginTime:{},endTime:{},cosTime:{},dubbo返回:{},aid:{}", beginTime,endTime,(endTime-beginTime),albumInfoDto != null ? albumInfoDto.getReturnCode() : "null",aid); } if (albumInfoDto == null) { return fallback(); } String key = String.format(CommonUtil.Get_AlbumInfo_ByDubbo, aid); if (albumInfoDto.getReturnCode() == 0) { serviceManager.getRedisClusterHyStrix().setex(key, CommonUtil.timeout, SerializationUtil.object2Bytes(albumInfoDto)); } else { logger.info(" ====== GetAlbumInfoByDubboCommand,获取专辑信息时,dubbo返回:{},aid:{}",albumInfoDto.getReturnCode(),aid); serviceManager.getRedisClusterHyStrix().del(key); //不等于0说明专辑失效或删除,需要删除hystrix的缓存 } return albumInfoDto; } @Override public void alert() { logger.error(" ================================================== GetAlbumInfoByDubboCommand into CircuitBreaker"); String key = "AlbumInfo"; if (StringUtils.isEmpty(serviceManager.getRedisClusterHyStrix().get(key))) { WxSmsUtils.getInstance().warnByWx("AlbumInfo-Into-[CircuitBreaker]"); serviceManager.getRedisClusterHyStrix().setex(key,CommonUtil.WARN_WX_TIMEOUT,key); } } /** * @author liweihan * @time 2017/11/13 17:12 * @description 统计一下某个dubbo方法的次数 * @param key */ public void incr(String key) { try { serviceManager.getRedisCluster().incr(key); } catch (Exception e) { logger.error(" ====== redis操作出现异常!key:{}",key,e); } }}复制代码

获得基础信息-UserInfo的Command类

package com.xxx.xxx.xxx.data.command.dubbo;import com.xxx.xxx.xxx.service.ServiceManager;import com.xxx.xxx.xxx.util.CommonUtil;import com.xxx.xxx.xxx.util.SerializationUtil;import com.xxx.xxx.xxx.util.WxSmsUtils;import com.xxx.xxx.xxx.midware.dubbo.api.dto.UserInfoDto;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * @author liweihan * @time 2017/10/11 15:12 * @description 获取PGC/UGC用户基础信息! */public class GetUserInfoByDubboCommand extends AbstractDubboCommand
{ public static final Logger logger = LoggerFactory.getLogger(GetUserInfoByDubboCommand.class); Long userId; ServiceManager serviceManager; public GetUserInfoByDubboCommand(Long userId , ServiceManager serviceManager) { super("GetUserInfo"); this.userId = userId; this.serviceManager=serviceManager; } @Override public UserInfoDto fallback() { String key = String.format(CommonUtil.Get_UserInfo_ByDubbo, userId); logger.info(" GetUserInfoByDubboCommand from dubbo fail,key:{}",key); byte[] obj = serviceManager.getRedisClusterHyStrix().getBytes(key); try { UserInfoDto userInfoDto = (UserInfoDto)SerializationUtil.bytes2Object(obj); return userInfoDto; }catch (Exception e) { logger.error(" ====== GetUserInfoByDubboCommand from Hystrix'fallback error,key:{} . Exception:{}" ,key,e); } return null; } @Override protected UserInfoDto run() throws Exception { UserInfoDto userInfoDto = null; long beginTime = System.currentTimeMillis(); try { /** * http://mwiki.sohuno.com/pages/viewpage.action?pageId=32866496 */ userInfoDto = serviceManager.getDubboUserService().userInfo(userId); } catch (Exception e) { logger.error(" ====== GetUserInfoByDubboCommand ,调用dubbo出错!userId:{}",userId,e); } //统计一下该dubbo的访问次数// incr("dubbo_userinfo"); long endTime = System.currentTimeMillis(); if ((endTime - beginTime) > CommonUtil.TIME_OUT_DUBBO_300) { //统计一下该dubbo的访问次数// incr("dubbo_userinfo_timeout"); logger.warn(" ====== GetUserInfoByDubboCommand ,调用dubbo时间久!beginTime:{},endTime:{},cosTime:{},dubbo返回:{},userId:{}", beginTime,endTime,(endTime-beginTime),userInfoDto != null ? userInfoDto.getReturnCode() : "null",userId); } if (userInfoDto == null) { return fallback(); } String key = String.format(CommonUtil.Get_UserInfo_ByDubbo, userId); if (userInfoDto.getReturnCode() == 0) { serviceManager.getRedisClusterHyStrix().setex(key, CommonUtil.timeout, SerializationUtil.object2Bytes(userInfoDto)); } else { logger.info(" ====== GetUserInfoByDubboCommand,获取用户信息时,dubbo返回:{},userId:{}",userInfoDto.getReturnCode(),userId); serviceManager.getRedisClusterHyStrix().del(key); } return userInfoDto; } @Override public void alert() { logger.error(" ================================================== GetUserInfoByDubboCommand into CircuitBreaker"); String key = "GetUserInfo"; if (StringUtils.isEmpty(serviceManager.getRedisClusterHyStrix().get(key))) { WxSmsUtils.getInstance().warnByWx("GetUserInfo-Into-[CircuitBreaker]"); serviceManager.getRedisClusterHyStrix().setex(key,CommonUtil.WARN_WX_TIMEOUT,key); } } /** * @author liweihan * @time 2017/11/13 17:12 * @description 统计一下某个dubbo方法的次数 * @param key */ public void incr(String key) { try { serviceManager.getRedisCluster().incr(key); } catch (Exception e) { logger.error(" ====== redis操作出现异常!key:{}",key,e); } }}复制代码

再其他的类也是类似的用法,你可以调用Http,RPC等第三方接口!写法都是类似的。

此处熔断后,进入Fallback读取备用缓存数据,如果缓存没有的话,再给用户返回null。这是一种策略。仅供参考 。

转载于:https://juejin.im/post/5c638085e51d456177631b66

你可能感兴趣的文章
SSL连接建立过程分析(1)
查看>>
port与大全portClose方法
查看>>
美丽的数学家:如果您讨厌数学,这些其实都是人生故事
查看>>
Kettle 中转换(transformation)的执行过程
查看>>
读书笔记-互联网思维阅读10其中一本书《自由》
查看>>
Spark入门实战系列--5.Hive(上)--Hive介绍及部署
查看>>
tomcat设置web根目录
查看>>
CF 444B(DZY Loves FFT-时间复杂度)
查看>>
OCP-1Z0-051-名称解析-文章12称号
查看>>
UVALive 4225 Prime Bases 贪心
查看>>
Oracle B-tree、位图、全文索引三大索引性能比较及优缺点汇总
查看>>
[.net 面向对象程序设计进阶] (20) 反射(Reflection)(上)利用反射技术实现动态编程...
查看>>
【转】java中float与byte[]的互转 -- 不错
查看>>
[Ogre][地形][原创]基于OgreTerrain的地形实现
查看>>
shell登录模式及其相应配置文件(转)
查看>>
Puppet常识梳理
查看>>
web.config配置文件中的configSource属性
查看>>
发现一个国内牛逼的maven仓库,速度真的太快了
查看>>
Snmp配置
查看>>
使用java实现CNN的实战
查看>>