标签:for 脚本 body lse call bsp code fan new
编写LUA脚本
该脚本功能:先检查redis中某个key的值是否与期望的值V1一致,如果一致则将其修改为新的值V2并返回true,否则返回false。其实就是CAS。
local current = redis.call(‘GET‘, KEYS[1]) if current == ARGV[1] then redis.call(‘SET‘, KEYS[1], ARGV[2]) return true end return false
注意,lua脚本中的变量都要是local 的,不可以是全局变量。否则会报错。详见 http://doc.redisfans.com/script/eval.html#id6
使用DefaultRedisScript加载lua脚本
@Bean public DefaultRedisScript<Boolean> redisScript() { DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(); redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/checkandset.lua"))); redisScript.setResultType(Boolean.class); return redisScript; }
测试
@Autowired DefaultRedisScript<Boolean> redisScript; /** * 测试redis lua * * @return */ @RequestMapping(value = "testredislua", method = {RequestMethod.GET}) @ResponseBody public Object testredislua() { String key = "testredislua"; redisTemplate.delete(key); redisTemplate.opsForValue().set(key, "hahaha"); String s = redisTemplate.opsForValue().get(key); log.info(s); redisTemplate.execute(redisScript, Collections.singletonList(key), "hahaha", "3333"); s = redisTemplate.opsForValue().get(key); log.info(s); return null; }
标签:for 脚本 body lse call bsp code fan new
原文地址:https://www.cnblogs.com/senlinyang/p/8830577.html