java 操作redis工具类

1.添加maven的包
<!-- Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.添加redis配置
spring.redis.database=1
spring.redis.host=127.0.0.1
#spring.redis.password=testpassword
spring.redis.port=6379
spring.redis.timeout=5000
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
3.redis操作类
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Author:   linjunit
 * Version:Redis工具类
 * Date:     2020/6/12 0012
 * Description:
 * Modification  History:
 * Date            Author            Version            Description
 * --------------------------------------------------------------
 * Why & What is modified:
 */
@Component
@Slf4j
public class RedisClient {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private static final String COLON = ":";
    /**
     * 存储到redis中的锁标志
     */
    private static final String LOCKED = "LOCKED";
    /**
     * 默认请求锁的超时时间(ms 毫秒)
     */
    private static final long TIME_OUT = 100;
    /**
     * 锁flag
     */
    private volatile boolean isLocked = false;

    /**
     * 缓存字符串
     *
     * @param table 表
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean set(String table, String key, String value) {
        try {
            key = table.equals("") ? key : table + COLON + key;
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * 缓存字符串
     *
     * @param table      表
     * @param key        键
     * @param value      值
     * @param expireTime 过期时间(秒)
     * @return
     */
    public boolean set(String table, String key, String value, long expireTime) {
        try {

            key = table.equals("") ? key : table + COLON + key;
            stringRedisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * 缓存对象
     *
     * @param table 表
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean set(String table, String key, Object value) {
        try {
            String json = JSON.toJSONString(value);
            return this.set(table, key, json);
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * 缓存对象
     *
     * @param table      表
     * @param key        键
     * @param value      值
     * @param expireTime 过期时间(秒)
     * @return
     */
    public boolean set(String table, String key, Object value, long expireTime) {
        try {
            String json = JSON.toJSONString(value);
            return this.set(table, key, json, expireTime);
        } catch (Exception ex) {
            return false;
        }
    }


    /**
     * 根据键取缓存数据
     *
     * @param table 表
     * @param key   键
     * @return 缓存数据
     */
    public String get(String table, String key) {
        try {
            key = table.equals("") ? key : table + COLON + key;
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception ex) {
            return "";
        }
    }

    /**
     * 根据键获取缓存对象
     *
     * @param table
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T get(String table, String key, Class<T> clazz) {
        try {
            key = table.equals("") ? key : table + COLON + key;
            String json = stringRedisTemplate.opsForValue().get(key);
            return JSON.parseObject(json, clazz);
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 根据键删除缓存数据
     *
     * @param table
     * @param key
     * @return
     */
    public boolean del(String table, String key) {
        try {
            key = table.equals("") ? key : table + COLON + key;
            return stringRedisTemplate.delete(key);
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * 设置分布式Redis锁
     *
     * @param table      表
     * @param key        键
     * @param expireTime 过期时间(秒)
     * @return
     */
    public boolean lock(String table, String key, long expireTime) {
        long nowTime = System.nanoTime();
        long timeout = TIME_OUT * 1000000;
        final Random random = new Random();
        key = table.equals("") ? key : table + COLON + key;

        while ((System.nanoTime() - nowTime) < timeout) {
            boolean result = redisTemplate.opsForValue().setIfAbsent(key, LOCKED);

            if (result) {
                isLocked = true;
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
                break;
            }
            try {
                Thread.sleep(10, random.nextInt(50000));
            } catch (InterruptedException e) {
                log.error("获取分布式锁休眠被中断:", e);
            }
        }
        return isLocked;
    }

    /**
     * 根据键判断是否有分布式锁
     *
     * @param table 表
     * @param key   键
     * @return
     */
    public boolean isLock(String table, String key) {
        key = table.equals("") ? key : table + COLON + key;
        redisTemplate.getConnectionFactory().getConnection().time();
        return redisTemplate.hasKey(key);
    }

    /**
     * 释放分布式Redis锁
     *
     * @param table 表
     * @param key   键
     */
    public void unlock(String table, String key) {
        // 释放锁
        // 不管请求锁是否成功,只要已经上锁,客户端都会进行释放锁的操作
        if (isLocked) {
            key = table.equals("") ? key : table + COLON + key;
            redisTemplate.delete(key);
        }
    }

    /**
     * 获取访问次数
     *
     * @param table      表
     * @param key        键
     * @param expireTime 过期时间(秒)
     * @return
     */
    public int getCount(String table, String key, long expireTime) {
        key = table.equals("") ? key : table + COLON + key;
        int resultCount = Math.toIntExact(redisTemplate.opsForValue().increment(key, 1));
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        return resultCount;
    }

    /**
     * 获取第二天零时失效的时间
     *
     * @return expireTime 过期时间(秒)
     */
    public Long getSecondsNextEarlyMorning() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }
}

4.简单的存储/获取redis

 

@Autowired
private RedisClient redis;
redis.set("uds_userToken", "uds_userToken", result);
StoreUserInfoOutput user = redis.get("uds_userToken",token,StoreUserInfoOutput.class);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值