spring boot 集成redisson与redisson lua脚本

spring boot 集成redisson与redisson lua脚本,第1张

版本说明
  • Spring Boot 版本:2.6.1
  • redis 版本:6.2.6
依赖
<dependency>
    <groupId>org.redissongroupId>
    <artifactId>redisson-spring-boot-starterartifactId>
    <version>3.13.6version>
dependency>
连接地址配置
redis.address=127.0.0.1:6379
redis.password=123456
配置文件
@Configuration
public class RedisConfiguration {

    @Value("${redis.address}")
    private String redis_address;
    @Value("${redis.password}")
    private String redis_password;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() {
        Config config = new Config();
        config.setTransportMode(TransportMode.NIO);
        config.useSingleServer()
                .setAddress("redis://" + redis_address)
                .setPassword(redis_password);
        return Redisson.create(config);
    }
}
redisson执行lua脚本
// \u0008表示数据的长度
// 前面\u0004不懂为啥是这个
// 不这样设置,get就无法获取数据,有大佬懂的可以指教下
redisson.getScript().evalAsync(
        RScript.Mode.READ_WRITE,
        "return redis.call('set', 'name', '\u0004>\u0008zhangsan'); ",
        RScript.ReturnType.MAPVALUELIST
).get();

// 通过传参就不会有这个问题
private void setValue(String key, String value) throws ExecutionException, InterruptedException {
    redisson.getScript().evalAsync(
            RScript.Mode.READ_WRITE,
            "return redis.call('set', KEYS[1], ARGV[1]);",
            RScript.ReturnType.MAPVALUELIST,
            Arrays.asList(key),
            value).get();
}

redisson.getScript().evalAsync(
        RScript.Mode.READ_WRITE, 
        "return redis.call('get', 'name'); ", 
        RScript.ReturnType.MAPVALUELIST
).get();

要是遇到在lua脚本中进行一些计算然后返回数据就特别麻烦了,例如中文字符的长度

// 计算字符串长度脚本
"local function widthSingle(str) " +
    "local lenInByte = #str; " +
    "local width = 0; " +
    "local i = 1; " +
    "while (i<=lenInByte) do " +
        "local curByte = string.byte(str, i); " +
        "local byteCount = 1; " +
        "if curByte>0 and curByte<=127 then " +
            "byteCount = 1; " +
        "elseif curByte>=192 and curByte<223 then " +
            "byteCount = 2; " +
        "elseif curByte>=224 and curByte<239 then " +
            "byteCount = 3; " +
        "elseif curByte>=240 and curByte<=247 then " +
            "byteCount = 4; " +
        "end; " +
        "local char = string.sub(str, i, i+byteCount-1); " +
        "i = i + byteCount; " +
        "width = width + 1; " +
    "end; " +
"return width; end; "

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

原文地址: http://outofmemory.cn/langs/720482.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存