package com.amway.msgcenter.msgtask.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.Redistemplate;
import org.springframework.data.redis.core.StringRedistemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCommands;
@Component
public class RedisUtil {
@Autowired
// 操作字符串的template,StringRedistemplate是Redistemplate的一个子集
private StringRedistemplate stringRedistemplate;
@Autowired
// Redistemplate,可以进行所有的操作
private Redistemplate<Object, Object> redistemplate;
public void set(String key, String value) {
stringRedistemplate.opsForValue().set(key, value);
}
public void set(String key, String value, long time) {
stringRedistemplate.opsForValue().set(key, value, time);
}
public String get(String key) {
return stringRedistemplate.opsForValue().get(key);
}
public void delete(String key) {
stringRedistemplate.delete(key);
}
public Long getLock(String lockKey, String value, int time) {
return redistemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
Long result = commands.setnx(lockKey, value);
commands.expire(lockKey, time);
return result;
}
});
}
public String getLock2(String lockKey, String value, int time) {
return redistemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
return commands.set(lockKey, value, "NX", "PX", time * 1000L);
}
});
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。