redis使用工具类

redis 属性加载

package com.example.mybatisplus;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public JedisPool redisPoolFactory() {
        logger.info("JedisPool注入成功!!");
        logger.info("redis地址:" + host + ":" + port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
        return jedisPool;
    }
}

工具类一

package com.kingxunlian.purchase.suppliermanagement.config;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
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 org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author miwei~
 * 基于spring和redis的StringRedisTemplate工具类
 */
@Component
public class RedisUtil<T> {
    
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    //=============================common============================
    
    /**
     * 向redis里存入数据和设置缓存时间
     * @param key 缓存key
     * @param val 缓存的值
     * @param seconds 超时时间
     */
    public void set(String key, String val, Long seconds) {
        if (seconds != null) {
            this.stringRedisTemplate.opsForValue().set(key, val, seconds, TimeUnit.SECONDS);
        } else {
            this.stringRedisTemplate.opsForValue().set(key, val);
        }
    }
    
    public String get(String key) {
        return this.stringRedisTemplate.opsForValue().get(key);
    }
    
    public T getObject(String key, Class<T> clazz) {
        String value = this.stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(value)) {
            return JSON.parseObject(value, clazz);
        }
        return null;
    }
    
    
    /**
     * 根据key值,增或减去val的值
     * @param key 缓存key
     * @param val 负数为减值,正数为加
     */
    public Long increment(String key, long val) {
        BoundValueOperations boundValueOperations = this.stringRedisTemplate.boundValueOps(key);
        Long increment = boundValueOperations.increment(val);
        if (increment == null || increment.longValue() == 0) {
            boundValueOperations.expire(1, TimeUnit.DAYS);
        }
        return increment;
    }
    
    
    /**
     * 根据key删除缓存
     * @param key 缓存key
     */
    public void delete(String key) {
        this.stringRedisTemplate.delete(key);
    }

    @Autowired
    RedisTemplate redisTemplate;
    public void rightPush(String key,Object obj){
        redisTemplate.opsForList().rightPush(key,obj);
    }

    public void leftPush(String key,Object obj){
        redisTemplate.opsForList().leftPush(key,obj);
    }

    public List<Object> getList(String key){
        return redisTemplate.opsForList().range(key,0,-1);
    }

    public void delete(String key,long count,Object obj){
        redisTemplate.opsForList().remove(key,count,obj);
    }

    public void expire(String key,Integer seconds){
        redisTemplate.expire(key,seconds,TimeUnit.SECONDS);
    }

    public Object getFrist(String key){
        List list = redisTemplate.opsForList().range(key,0,0);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }
}

工具类二

package com.example.mybatisplus.utils;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;


@Component
public class RedisTemplateHelper {
    /**
     * 初始化
     */
    private static RedisTemplateHelper redisTemplateHelper;
    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void init() {
        redisTemplateHelper = this;
        redisTemplateHelper.redisTemplate = this.redisTemplate;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public static boolean set(String key, Object value) {
        boolean result = false;
        try {
            @SuppressWarnings("unchecked")
            ValueOperations<Serializable, Object> operations = redisTemplateHelper.redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    @SuppressWarnings("unchecked")
    public static boolean set(String key, String value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, String> operations = redisTemplateHelper.redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplateHelper.redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public static void remove(String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    @SuppressWarnings("unchecked")
    public static void removePattern(String pattern) {
        Set<Serializable> keys = redisTemplateHelper.redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplateHelper.redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    @SuppressWarnings("unchecked")
    public static void remove(String key) {
        if (exists(key)) {
            redisTemplateHelper.redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public static boolean exists(String key) {
        return redisTemplateHelper.redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        Object result = null;
        @SuppressWarnings("unchecked")
        ValueOperations<Serializable, Object> operations = redisTemplateHelper.redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 哈希 添加
     *
     * @param key
     * @param hashKey
     * @param value
     */
    public static void hmSet(String key, Object hashKey, Object value) {
        @SuppressWarnings("unchecked")
        HashOperations<String, Object, Object> hash = redisTemplateHelper.redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
    public static Object hmGet(String key, Object hashKey) {
        @SuppressWarnings("unchecked")
        HashOperations<String, Object, Object> hash = redisTemplateHelper.redisTemplate.opsForHash();
        return hash.get(key, hashKey);
    }

    /**
     * 列表添加
     *
     * @param k
     * @param v
     */
    public static void lPush(String k, Object v) {
        @SuppressWarnings("unchecked")
        ListOperations<String, Object> list = redisTemplateHelper.redisTemplate.opsForList();
        list.rightPush(k, v);
    }

    /**
     * 列表获取
     *
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public static List<Object> lRange(String k, long l, long l1) {
        @SuppressWarnings("unchecked")
        ListOperations<String, Object> list = redisTemplateHelper.redisTemplate.opsForList();
        return list.range(k, l, l1);
    }

    /**
     * 集合添加
     *
     * @param key
     * @param value
     */
    public static void add(String key, Object value) {
        @SuppressWarnings("unchecked")
        SetOperations<String, Object> set = redisTemplateHelper.redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     *
     * @param key
     * @return
     */
    public static Set<Object> setMembers(String key) {
        @SuppressWarnings("unchecked")
        SetOperations<String, Object> set = redisTemplateHelper.redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     *
     * @param key
     * @param value
     * @param scoure
     */
    public static void zAdd(String key, Object value, double scoure) {
        @SuppressWarnings("unchecked")
        ZSetOperations<String, Object> zset = redisTemplateHelper.redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     *
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public static Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        @SuppressWarnings("unchecked")
        ZSetOperations<String, Object> zset = redisTemplateHelper.redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值