spring boot 集成redisson与redisson lua脚本

版本说明

  • Spring Boot 版本:2.6.1
  • redis 版本:6.2.6

依赖

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.13.6</version>
</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; "
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值