月光代碼園

記錄、分享、交流

导航

Redis学习笔记#10 lua脚本,整合springboot调用

lua代码:

-- checkandset.lua local current = redis.call('GET', KEYS[1]) if current == ARGV[1] then redis.call('SET', KEYS[1], ARGV[2]) return true end return false

 

配置:

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

  RedisTemplate<String, Object> template = new RedisTemplate<>();  
  template.setConnectionFactory(factory);
  template.setKeySerializer(new StringRedisSerializer());
  template.setValueSerializer(new StringRedisSerializer());
  return template;
}


@Bean
public RedisScript<Boolean> redisScript() {   DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(); ScriptSource scriptSource = new ResourceScriptSource(new ClassPathResource("META-INF/scripts/checkandset.lua")); redisScript.setResultType(Boolean.class); redisScript.setScriptSource(scriptSource); return redisScript;
}

 

调用:

@Autowired
RedisTemplate redisTemplate;

@Autowired
RedisScript<Boolean> redisScript;

List<String> keys = new ArrayList<>();
keys.add("stock");
return redisTemplate.execute(redisScript, keys, 2);

  

posted on 2020-04-26 13:17  bangdikka  阅读(309)  评论(0编辑  收藏  举报