redis list数据结构实现队列

消息队列的好处

提高响应速度、解耦、稳定性(故障处理)、可扩展性、有序性、异步性

redis实现消息队列方法

  • 抓取异常,封装异常对象,插入redis队列中
try{
    // 业务代码
}catch (ServiceException e){
    // 异常信息封装
    Access access = '封装逻辑';
    // 调用redis 
    redisSentinelProxy.Lpush(errorCode, access);
    continue;
}


  • 监听redis队列
@Component
@Slf4j
public class AccessRedis {

    // 线程数
    private int threadNum = 5;
    
    if (threadNum <= 0) {
        threadNum = 5;
    }

    // 此注解的作用在对象注入容器后执行给注解修饰的方法,且只执行一次
    @PostConstruct
    public void init() {
       for (int i = 0; i <= threadNum ; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 此方法内部为死循环从redis队列中读取数据,有就处理,没有就继续循环
                    accessHandler.doBusiness(null);
                }
            }).start();
        }
    }

}



@Service
public class AccessHandler {

    boolean flag = true;
    // 死循环
    while (flag) {
        try {
         // 从redis队列中读取数据
         TAccess access = redisSentinelProxy.bRpop(errorCode, 0, TAccess.class);
         // 异常信息如表
         sql语句
        } catch () {
           
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_36042938/article/details/112581149
今日推荐