您好,登錄后才能下訂單哦!
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);
}
});
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。