温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

RedisUtil 工具类

发布时间:2020-07-23 17:14:22 来源:网络 阅读:238 作者:IT达仁 栏目:软件技术

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);

        }
    });

}

}

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI