首先在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]