栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

redis宕机后设置的redis连接超时时间还有效吗

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

redis宕机后设置的redis连接超时时间还有效吗

博客主页:https://blog.csdn.net/GBS20200720
博主昵称:怎么又有bug单
主要领域:Java、Linux、K8S
期待大家的关注点赞收藏⭐留言

文章目录
  • 原因
  • 代码
    • ConsumeConfiguration:
    • MyRunnable01:
    • ProduceRequest:
    • QueueNameEnum:
    • RedisController:
    • RedisUtil:
    • TaskScheduleController:
    • application.yml:
    • 说明:
    • 现象:
  • 结论:

原因

redis宕机后,设置的redis连接超时时间还有效吗?

最近在实际的开发中遇到了这个问题。大家要模拟redis故障的场景,观察业务系统会受多大的影响,会不会阻塞主流程。
而在模拟redis宕机之后,发现之前设置的超时时间并未生效。现象是超时时间设置了1000ms,但是实际调用redis服务返回快速失败只用了20ms,这说明超时时间并未生效。

于是我自己写了一个demo,来验证下redis宕机后,设置的redis连接超时时间是否还有效。

代码 ConsumeConfiguration:
public class ConsumeConfiguration {
    @Autowired
    private RedisUtil redisUtil;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 模仿消费者  每秒执行一次
    @Scheduled(cron = "*/1 * * * * * ")
    public void consume(){
        System.out.println("------------等待消费--------------");
        // 取出QUEUE_NAME集合中的score在0-当前时间戳这个范围的所有值
        Set set = redisUtil.opsForZSetrangeByScore(QueueNameEnum.REDIS_DELAY_QUEUE01.getMsg(), 0, System.currentTimeMillis());
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Integer value = (Integer) iterator.next();
            // 遍历取出每一个score
            Double score = redisUtil.opsForZSetScore(QueueNameEnum.REDIS_DELAY_QUEUE01.getMsg(), value);
            // 达到了时间就进行消费
            if (System.currentTimeMillis() > score) {
                System.out.println("消费了:" + value + "消费时间为:" + simpleDateFormat.format(System.currentTimeMillis()));
                redisUtil.opsForZSetRemove(QueueNameEnum.REDIS_DELAY_QUEUE01.getMsg(), value);

            }
        }
    }
}

 
MyRunnable01: 
@Component
public class MyRunnable01 implements Runnable {

    @Autowired
    private RedisUtil redisUtil;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void run() {

        // 模仿消费者  每秒执行一次
        // 取出QUEUE_NAME集合中的score在0-当前时间戳这个范围的所有值
        Set set = redisUtil.opsForZSetrangeByScore(QueueNameEnum.REDIS_DELAY_QUEUE01.getMsg(), 0, System.currentTimeMillis());
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Integer value = (Integer) iterator.next();
            // 遍历取出每一个score
            Double score = redisUtil.opsForZSetScore(QueueNameEnum.REDIS_DELAY_QUEUE01.getMsg(), value);
            // 达到了时间就进行消费
            if (System.currentTimeMillis() > score) {
                System.out.println("消费了:" + value + "消费时间为:" + simpleDateFormat.format(System.currentTimeMillis()));
                redisUtil.opsForZSetRemove(QueueNameEnum.REDIS_DELAY_QUEUE01.getMsg(), value);

            }
        }
    }


}

 
ProduceRequest: 
@Data
public class ProduceRequest {
    // 发送消息的code
    // 1为1号消息 2为2号消息 3为3号消息
    private Integer messageCode;
    // 多少秒之后消费
    private Integer afterSeconds;
    // 消息内容
    private String message;
    // 发送条数
    private Integer number;
}

QueueNameEnum:
public enum QueueNameEnum {
    REDIS_DELAY_QUEUE01(1, "redis_delay_queue01"),
    REDIS_DELAY_QUEUE02(2, "redis_delay_queue02"),
    REDIS_DELAY_QUEUE03(3, "redis_delay_queue03");

    private int code;
    private String msg;

    QueueNameEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public static String getMsgByCode(int code) {
        switch (code) {
            case 1: {
                return REDIS_DELAY_QUEUE01.getMsg();
            }
            case 2: {
                return REDIS_DELAY_QUEUE02.getMsg();
            }
            case 3: {
                return REDIS_DELAY_QUEUE03.getMsg();
            }
        }
        return REDIS_DELAY_QUEUE03.getMsg();
    }

}

RedisController:
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisUtil redisUtil;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 模仿生产者
    @RequestMapping("/product")
    public String product01(@RequestBody ProduceRequest produceRequest) {
        String message = produceRequest.getMessage();
        Integer afterSeconds = produceRequest.getAfterSeconds();
        Integer number = produceRequest.getNumber();
        Integer messageCode = produceRequest.getMessageCode();
        // 01号消息发送10条
        for (int i = 1; i <= number; i++) {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());
            // 获取当前秒数 并把消费时间设为当前时间的20秒以后
            now.set(Calendar.SECOND, now.get(Calendar.SECOND) + afterSeconds);
            System.out.println("生产了:" + message + "当前时间为:" + simpleDateFormat.format(System.currentTimeMillis()) + "消费时间为:" + simpleDateFormat.format(now.getTime()));
            // 往QUEUE_NAME这个集合中放入i,设置score为排序规则
            redisUtil.opsForZsetAdd(QueueNameEnum.getMsgByCode(messageCode) + i, message, now.getTime().getTime());
        }
        return "生产者生产消息成功";
    }
}
RedisUtil:
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    //=============================common============================
    //将 {value} 添加到 {key} 处的排序集合,或者如果它已经存在则更新其 {score}
    public void opsForZsetAdd(String key, V value, double score){
        redisTemplate.opsForZSet().add(key, value, score);
    }

    public Set opsForZSetrangeByScore(String key, double min, double max){
        return  redisTemplate.opsForZSet().rangeByScore(key, min, max);
    }

    
    public boolean expire(String key,long time){
        try {
            if(time>0){
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @SuppressWarnings("unchecked")
    public void del(String ... key){
        if(key!=null&&key.length>0){
            if(key.length==1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    //============================String=============================
    
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    }

    
    public boolean set(String key,Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    
    public boolean set(String key,Object value,long time){
        try {
            if(time>0){
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }else{
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public long incr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    
    public long decr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    //================================Map=================================
    
    public Object hget(String key,String item){
        return redisTemplate.opsForHash().get(key, item);
    }

    
    public Map hmget(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    
    public boolean hmset(String key, Map map){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean hmset(String key, Map map, long time){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean hset(String key,String item,Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean hset(String key,String item,Object value,long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public void hdel(String key, Object... item){
        redisTemplate.opsForHash().delete(key,item);
    }

    
    public boolean hHasKey(String key, String item){
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    
    public double hincr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    
    public double hdecr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(key, item,-by);
    }

    //============================set=============================
    
    public Set sGet(String key){
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    
    public boolean sHasKey(String key,Object value){
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public long sSet(String key, Object...values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    
    public long sSetAndTime(String key,long time,Object...values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if(time>0) expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    
    public long sGetSetSize(String key){
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    
    public long setRemove(String key, Object ...values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    //===============================list=================================

    
    public List lGet(String key,long start, long end){
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    
    public long lGetListSize(String key){
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    
    public Object lGetIndex(String key,long index){
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean lSet(String key, List value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean lSet(String key, List value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean lUpdateIndex(String key, long index,Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public long lRemove(String key,long count,Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    // 获取zset中指定key的score
    public Double opsForZSetScore(String key, Object score) {
        return redisTemplate.opsForZSet().score(key, score);
    }

    // zset删除元素
    public void opsForZSetRemove(String key, Object value) {
        redisTemplate.opsForZSet().remove(key, value);
    }
}

 
TaskScheduleController: 
@RestController
@RequestMapping("/task")
public class TaskScheduleController {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    private MyRunnable01 myRunnable;

    private ScheduledFuture future1;


    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    // 手动执行定时任务
    // 每秒尝试消费01号消息一次
    @RequestMapping("/startconsume01")
    public String startCron1() {

        future1 = threadPoolTaskScheduler.schedule(myRunnable, new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
                return new CronTrigger("0/1 * * * * *").nextExecutionTime(triggerContext);
            }
        });
        return "定时任务启动成功!";
    }

    @RequestMapping("/stopconsume01")
    public String stopCron1() {
        if (future1 != null) {
            future1.cancel(true);
        }
        return "定时任务关闭成功!";
    }



}

application.yml:
server:
  port: 8888
redis:
  host: 127.0.0.1
  port: 6379
  timeout: 3000
  jedis:
    pool:
      max-idle: 500
      min-idle: 50
      max-active: 2000
      max-wait: 1000
  testOnBorrow: true
说明:

这里的场景是:
使用redis做一个延时消费,而此时我并没有启动redis,也相当于redis已宕机

现象:

启动项目,发出rest请求:

观察控制台:

可以看到是瞬间报错,与我设置的3000ms超时时间并没有任何关系。

结论:

所以redis宕机后,设置的连接超时时间是不会生效的。

超时时间只会在redis启动,但是繁忙的时候,有效。

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号