java 操作redis工具类

1.添加maven的包


    org.springframework.boot
    spring-boot-starter-data-redis
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 
     * @return
     */
    public  T get(String table, String key, Class 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);

 

你可能感兴趣的:(常用帮助类整理,java,redis,client,示例,redis,缓存,java)