Java对Redis的简单封装

Java对Redis的简单封装

相关文章:
Linux安装Redis
SpringBoot连接Redis
Redis常见问题
Redis实现主从复制

封装说明:

项目中对于Redis的简单封装,仅供参考学习使用,不完全保证生产环境中不会出现问题

方法汇总:

  • 存储对象,不设置过期时间
  • 存储对象,设置过期时间
  • 获取对象
  • 判断Key是否存在
  • 值自增
  • 值自减
  • Redis 充当分布式锁
  • 释放锁
  • Redis存放Hash
  • 获取hash值
  • 刷新过期时间

完整代码如下:


package com.xcx.cache.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;


/**
 * @Auther: chenlong
 * @Date: 2018/9/16 14:22
 * @Description:封装Redis
 */
@Service
public class RedisCache {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    //日志
    private Logger logger = LoggerFactory.getLogger(RedisCache.class);

    //维护获取锁的线程是否释放锁
    private Map<String, Boolean> map = new ConcurrentHashMap<>();

    //是否启用缓存,可用配置文件
    private boolean isCancel = false;


    /**
     * 存储对象,不设置过期时间
     *
     * @param key
     * @param val
     */
    public void setObj(String key, Object val) {
        if (isCancel)
            return;
        try {
            redisTemplate.opsForValue().set(key, val);
        } catch (Exception e) {
            logger.info("set opsForValue error" + e);
        }

    }

    /**
     * 存储对象,设置过期时间
     *
     * @param key
     * @param value
     * @param time
     */
    public void setObj(String key, String value, long time) {
        if (isCancel)
            return;
        try {
            redisTemplate.opsForValue().set(key, value);
            redisTemplate.expire(key, time, TimeUnit.MINUTES);
        } catch (Exception e) {
            logger.info("set opsForValue error" + e);
        }
    }

    /**
     * 获取对象
     *
     * @param key
     * @return
     */
    public Object getObj(String key) {
        if (isCancel)
            return null;
        if (!containKey(key))
            return null;
        Object o = redisTemplate.opsForValue().get(key);
        return o;
    }

    /**
     * 判断Key 是否存在
     *
     * @param key
     * @return
     */
    public boolean containKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 值自增
     *
     * @param key
     * @return
     */
    public long inc(String key) {
        redisTemplate.hasKey(key);
        long num = redisTemplate.opsForValue().increment(key);
        return num;
    }

    /**
     * 值自减
     *
     * @param key
     * @return
     */
    public long dec(String key) {
        long num = redisTemplate.opsForValue().decrement(key);
        return num;
    }

    public void delKey(String key) {
        if (containKey(key))
            redisTemplate.delete(key);
    }

    /**
     * Redis 充当分布式锁,uuid是释放锁时用
     *
     * @param key
     * @param expire
     */
    public boolean lock(String key, long expire, String uuid) {

        return (Boolean) redisTemplate.execute((RedisCallback) conn -> {
            Boolean result = conn.set(key.getBytes(), uuid.getBytes(), Expiration.from(expire, TimeUnit.SECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT);
            return result;

        });
    }


    /**
     * 释放锁,使用Lua语言来确保解锁操作是原子性的
     *
     * @param key
     * @return
     */
    public Boolean release(String key, String uuid) {
        return (Boolean) redisTemplate.execute((RedisCallback) conn -> {
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            Boolean result = conn.eval(script.getBytes(), ReturnType.BOOLEAN, 1, key.getBytes(), uuid.getBytes());
            return result;
        });
    }

    /**
     * Redis存放Hash
     *
     * @param key
     * @param map
     */
    public void setHash(String key, Map map) {
        if (isCancel)
            return;
        redisTemplate.opsForHash().putAll(key, map);
        //10分钟有效
        redisTemplate.expire(key, 5, TimeUnit.MINUTES);
    }

    /**
     * 获取hash值
     *
     * @param hashKey
     * @param mapKey
     * @return
     */

    public Object getHash(String hashKey, String mapKey) {
        if (isCancel)
            return null;
        if (!containKey(hashKey))
            return null;
        Object o;
        Map map = redisTemplate.opsForHash().entries(hashKey);
        o = map.get(mapKey);
        return o;
    }

    /**
     * 刷新过期时间
     *
     * @param key
     * @param time
     */
    public void refKey(String key, long time) {
        redisTemplate.expire(key, time, TimeUnit.MINUTES);
    }


}

你可能感兴趣的:(每天学Java之Redis)