springboot 2.x集成redis+lua脚本

springboot 2.x集成redis+lua脚本,第1张

springboot 2.x集成redis+lua脚本

文章目录
  • 一、springboot集成redis
    • 1、引Pom
    • 2、配置,我用的是cluster(当然集群不支持事物-我后面一些多命令会用Lua)
    • 3、redis数据类型序列化,这里我重命名了一下redisTemplateMy ,你也可以保持原名redisTemplate
    • 4 、搞一个工具类,大多数简单 *** 作的都比较适用
  • 二、原子 *** 作-lua脚本
    • 1、lua一些常见语法
    • 2、集成lua用法
    • 3、注意项

一、springboot集成redis 1、引Pom
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

        
            org.apache.commons
            commons-pool2
        
2、配置,我用的是cluster(当然集群不支持事物-我后面一些多命令会用Lua)
spring.redis.timeout = 10000ms
spring.redis.database = 0
spring.redis.password = jc_redis_xyz
spring.redis.cluster.nodes = ip1:7000,ip1:7001,ip2:7000,ip2:7001,ip3:7000,ip3:7001
spring.redis.cluster.max-redirects = 2
spring.redis.lettuce.pool.max-active = 1000
spring.redis.lettuce.pool.max-idle = 10
spring.redis.lettuce.pool.min-idle = 3
spring.redis.lettuce.pool.max-wait = 6000ms

本地或测试环境是单机的话,直接换成这个,你配置成哪种,springboot集成的redis自动装配会帮你切换使用哪种连接。所以只改配置就行了,用法不变:

spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis服务器连接密码(默认为空)
spring.redis.password=
#连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.pool.max-idle=8
#连接池中的最小空闲连接
spring.redis.pool.min-idle=0
#连接超时时间(毫秒)
spring.redis.timeout=30000
3、redis数据类型序列化,这里我重命名了一下redisTemplateMy ,你也可以保持原名redisTemplate
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    //redisConnectionFactory配置信息由yml控制

    @Bean
    @ConditionalOnMissingBean
    public RedisTemplate redisTemplateMy (LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate();
        //配置序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}
4 、搞一个工具类,大多数简单 *** 作的都比较适用
package com.epay.cu.upcc.ccc.provider.controller.test.redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtil {

  @Autowired
  private RedisTemplate redisTemplate;

  
  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));
      }
    }
  }
  // ================================Map=================================

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

  
  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 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 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);
  }

  // ============================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;
    }
  }


  
  public Set intersect(String key1, String key2) {
    try {
      return redisTemplate.opsForSet().intersect(key1, key2);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  //=================================zSet=============================

  
  public boolean sZset(String key, Object value, double score) {
    try {
      return redisTemplate.opsForZSet().add(key, value, score);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  
  public Long sZsetList(String key, Set> tuples) {
    try {
      return redisTemplate.opsForZSet().add(key, tuples);
    } catch (Exception e) {
      e.printStackTrace();
      return 0L;
    }
  }


  
  public Long zRemove(String key, Object... value) {
    try {
      return redisTemplate.opsForZSet().remove(key, value);
    } catch (Exception e) {
      e.printStackTrace();
      return 0L;
    }
  }

  
  public Double zIncrScore(String key, String value, double score) {
    try {
      return redisTemplate.opsForZSet().incrementScore(key, value, score);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  
  public Double zScore(String key, String value) {
    try {
      return redisTemplate.opsForZSet().score(key, value);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }


  
  public Long zRank(String key, String value) {
    try {
      return redisTemplate.opsForZSet().rank(key, value);
    } catch (Exception e) {
      e.printStackTrace();
      return -1L;
    }
  }
  
  public Set zRange(String key, int start, int end) {
    return redisTemplate.opsForZSet().range(key, start, end);
  }

  
  public Set reverseRange(String key, int start, int end) {
    return redisTemplate.opsForZSet().reverseRange(key, start, end);
  }


  
  public Set> rangeWithScore(String key, int start, int end) {
    return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
  }


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

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

  
  public Long zSize(String key) {
    return redisTemplate.opsForZSet().zCard(key);
  }


  // ===============================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 listRightPush(String key, Object value) {
    try {
      redisTemplate.opsForList().rightPush(key, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

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

  //


  
  public Object listLeftPop(String key) {
    try {
      return redisTemplate.opsForList().leftPop(key);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  
  public Object listLeftPop(String key, long time) {
    try {
      return redisTemplate.opsForList().leftPop(key,time, TimeUnit.SECONDS);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }


  
  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;
    }
  }


  
  public boolean lock(String lockKey, long lockExpireMils) {
    return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
      long nowTime = System.currentTimeMillis();
      Boolean acquire = connection.setNX(lockKey.getBytes(), String.valueOf(nowTime + lockExpireMils + 1).getBytes());
      if (acquire) {
        return Boolean.TRUE;
      } else {
        byte[] value = connection.get(lockKey.getBytes());
        if (Objects.nonNull(value) && value.length > 0) {
          long oldTime = Long.parseLong(new String(value));
          if (oldTime < nowTime) {
            //connection.getSet:返回这个key的旧值并设置新值。
            byte[] oldValue = connection.getSet(lockKey.getBytes(), String.valueOf(nowTime + lockExpireMils + 1).getBytes());
            //当key不存时会返回空,表示key不存在或者已在管道中使用
            return oldValue == null ? false : Long.parseLong(new String(oldValue)) < nowTime;
          }
        }
      }
      return Boolean.FALSE;
    });
  }

  
  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);
  }


  // ============================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);
  }
}


 
二、原子 *** 作-lua脚本 
1、lua一些常见语法 

这个就不详解了,比较简单。

2、集成lua用法

主要是通过下面这个方法来执行脚本(当然还有几个兄弟方法也可以用)。

 T org.springframework.data.redis.core.RedisTemplate#execute(Redisscript, java.util.List, java.lang.Object...)

代码示例:这里实现一个redis的list队列结构的多个元素一起pop的原子 *** 作(redis目前版本还没有批量pop的命令)

  @Test
    public void testLuaList() {
        //key
        String key="keyList";
        //每次取两个
        int sizeEach=2;
        //先往List放7个值
        List l = Arrays.asList("1", "2", "3", "4", "5", "6", "7");
        redisUtil.listRightPushAll(key, l);

        // ---lua 脚本---
        DefaultRedisscript redisscript = new DefaultRedisscript();
        // 1)指定 lua 脚本
        redisscript.setscriptSource(new ResourcescriptSource(new ClassPathResource("redis/ListPopN.lua")));
        // 2)指定返回类型,官方只支持4种:Long,Boolean,List,deserialized value
        redisscript.setResultType(List.class);
        try {
            getLuaList();
            List keys = Arrays.asList(key);
            // 3)执行lua脚本---参数一:redisscript,参数二:key列表,参数三:arg(可多个,里面..形成数组)
            List result1 = (List) redisTemplateMy.execute(redisscript, keys, sizeEach - 1);
            logger.info("{}[执行结果], keys={},result1={}", TAG, keys, JSON.toJSONString(result1));
            while (!result1.isEmpty() && result1.size() == sizeEach) {
                getLuaList();
                result1 = (List) redisTemplateMy.execute(redisscript, keys, sizeEach - 1);
                logger.info("{}[本次pop获取到的结果], keys={},result1={}", TAG, keys, JSON.toJSONString(result1));
            }
            getLuaList();
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getLuaList() {
        //查一下最新的List值
        List list = redisUtil.lGet("keyList", 0, -1);
        logger.info("{}[查一下最新的List值],list={}", TAG, JSON.toJSONString(list));
    }
 

对应的脚本,我是放在配置里,你可以放代码里

内容如下

local sizeIndex=ARGV[1]+1
local rlist = redis.call('lrange', KEYS[1],0,ARGV[1])
if #rlist == sizeIndex then
    redis.call('ltrim', KEYS[1],#rlist,-1)
    return  rlist
else
    return rlist;
end


测试demo

    @Test
    public void testLuaList() {
        //key
        String key="keyList";
        //每次取两个
        int sizeEach=2;
        //先往List放7个值
        List l = Arrays.asList("1", "2", "3", "4", "5", "6", "7");
        redisUtil.listRightPushAll(key, l);

        // ---lua 脚本---
        DefaultRedisscript redisscript = new DefaultRedisscript();
        // 1)指定 lua 脚本
        redisscript.setscriptSource(new ResourcescriptSource(new ClassPathResource("redis/ListPopN.lua")));
        // 2)指定返回类型,官方只支持4种:Long,Boolean,List,deserialized value
        redisscript.setResultType(List.class);
        try {
            getLuaList();
            List keys = Arrays.asList(key);
            // 3)执行lua脚本---参数一:redisscript,参数二:key列表,参数三:arg(可多个,里面..形成数组)
            List result1 = (List) redisTemplateMy.execute(redisscript, keys, sizeEach - 1);
            logger.info("{}[执行结果], keys={},result1={}", TAG, keys, JSON.toJSONString(result1));
            while (!result1.isEmpty() && result1.size() == sizeEach) {
                getLuaList();
                result1 = (List) redisTemplateMy.execute(redisscript, keys, sizeEach - 1);
                logger.info("{}[本次pop获取到的结果], keys={},result1={}", TAG, keys, JSON.toJSONString(result1));
            }
            getLuaList();
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getLuaList() {
        //查一下最新的List值
        List list = redisUtil.lGet("keyList", 0, -1);
        logger.info("{}[查一下最新的List值],list={}", TAG, JSON.toJSONString(list));
    }
 
3、注意项 
 T org.springframework.data.redis.core.RedisTemplate#execute(Redisscript, java.util.List, java.lang.Object...)

这个返回T是个泛型,入参时就得指定好,而且只支持4种类型,看以下spring-boot-starter-data-redis源码


不同版本的,差不多都是这意思

别乱用,不然会转换报错

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5671563.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)