美文网首页
SpringBoot整合Redis以及Lua脚本

SpringBoot整合Redis以及Lua脚本

作者: Hiper | 来源:发表于2022-11-14 20:43 被阅读0次

首先在application.yml中配置redis地址和端口号

spring:
  redis:
    host: localhost
    port: 6379

接着创建Redis和RedisScript配置类

@Configuration
public class RedisConfig {
    @Bean
    public StringRedisTemplate getStringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}
@Configuration
public class RedisScriptConfig {

    @Bean
    public DefaultRedisScript<String> defaultRedisScript() {
        DefaultRedisScript<String> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/redisScript.lua")));
        defaultRedisScript.setResultType(String.class);
        return defaultRedisScript;
    }
}

然后在方法中调用相应的方法

@RestController
@Slf4j
public class redisController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisScript<String> redisScript;

    @GetMapping("/test")
    public String test() {
        stringRedisTemplate.opsForValue().set("hello", "world!");
        stringRedisTemplate.opsForValue().set("hi", "morning!");
        List<String> redisKeys = Arrays.asList("hello", "hi");
        String result = stringRedisTemplate.execute(redisScript, redisKeys, "good!");
        log.info(result);
        return result;
    }
}

最后,RedisScriptConfig中的lua脚本内容为

return KEYS[1]..KEYS[2]..ARGV[1]

相关文章

网友评论

      本文标题:SpringBoot整合Redis以及Lua脚本

      本文链接:https://www.haomeiwen.com/subject/jqqrxdtx.html