千家信息网

RedisUtil 工具类

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,package com.amway.msgcenter.msgtask.util;import org.springframework.beans.factory.annotation.Autowir
千家信息网最后更新 2025年02月05日RedisUtil 工具类

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 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() {        @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() {        @Override        public String doInRedis(RedisConnection connection) throws DataAccessException {            JedisCommands commands = (JedisCommands) connection.getNativeConnection();            return commands.set(lockKey, value, "NX", "PX", time * 1000L);        }    });}

}

0