Redis和SpringBoot整合RedisUtils类

一、引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <!--<version></version>-->
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
        </dependency>

  

二、在application.yml 配置redis服务器

项目没完成,配置不在子项目中

 

 

三、写一个redis配置类

package com.nps.redis.config;

/*
 * @author XueWeiWei
 * @date 2019/8/29 15:38
 */

import com.nps.redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

@Configuration
@PropertySources({@PropertySource(
        value = {"classpath:nps-redis.properties","file:${xww.redis.config.file}"},
        encoding = "UTF-8",
        ignoreResourceNotFound = true
)})
public class RedisConfig {
    //idle 没有工作的
    //eviction 驱逐
    //cluster 团,簇
    @Value("${xww.redis.maxIdle}")
    private Integer maxIdle;
    @Value("${xww.redis.maxTotal}")
    private Integer maxTotal;
    @Value("${xww.redis.maxWaiMillis}")
    private Integer maxWaitMillis;
    @Value("${xww.redis.minEvictableIdleTimeMillis}")
    private Integer minEvictableIdleTimeMillis;
    @Value("${xww.redis.numTestsPerEvictionRun}")
    private Integer numTestsPerEvictionRun;
    @Value("${xww.redis.timeBetweenEvictionRunsMillis}")
    private long timeBetweenEvictionRunsMillis;
    @Value("${xww.redis.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${xww.redis.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${xww.redis.clusterNodes}")
    private String clusterNodes;
    @Value("${xww.redis.clusterMaxRedirects}")
    private Integer mmaxRedirectsac;

    public RedisConfig() {
    }

    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(this.maxIdle);
        jedisPoolConfig.setMaxIdle(this.maxTotal);
        jedisPoolConfig.setMaxWaitMillis(this.maxWaitMillis);
        jedisPoolConfig.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
        jedisPoolConfig.setNumTestsPerEvictionRun(this.numTestsPerEvictionRun);
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
        jedisPoolConfig.setTestOnBorrow(this.testOnBorrow);
        jedisPoolConfig.setTestWhileIdle(this.testWhileIdle);
        return jedisPoolConfig;
    }

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(){
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        String[] serverArray = this.clusterNodes.split(",");
        Set<RedisNode> nodes = new HashSet<>();
        String[] var4 = serverArray;
        int var5 = serverArray.length;

        for (int var6 = 0; var6 < var5; var6++) {
            String ipPort = var4[var6];
            String[] ipAndPort = ipPort.split(":");
            nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
        }

        redisClusterConfiguration.setClusterNodes(nodes);
        redisClusterConfiguration.setMaxRedirects(this.mmaxRedirectsac);
        return redisClusterConfiguration;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig, RedisClusterConfiguration redisClusterConfiguration){
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration, jedisPoolConfig);
        return  jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        this.iniDomainRedisTemplate(redisTemplate,redisConnectionFactory);
        return redisTemplate;
    }

    private void iniDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory redisConnectionFactory){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setEnableTransactionSupport(false);
        redisTemplate.setConnectionFactory(redisConnectionFactory);
    }

    @Bean(name = {"redisUtil"})
    public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate){
        RedisUtil redisUtil = new RedisUtil();
        redisUtil.setRedisTemplate(redisTemplate);
        return redisUtil;
    }

}

  

四、编写一个RedisUtil类

package com.nps.redis.utils;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

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

/*
 * @author XueWeiWei
 * @date 2019/8/30 11:19
 */
public class RedisUtil {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    private RedisTemplate<String, Object> redisTemplate;

    public RedisUtil() {
    }

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 指定缓存失效时间
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time){
        try{
            if (time > 0L){
                this.redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }

    }

    /**
     * 根据key获取过期时间
     * @param key
     * @return
     */
    public long getExpire(String key){
        return this.redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /**
     * 判断缓存中是否含有key
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        try{
            return this.redisTemplate.hasKey(key);
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 批量删除缓存
     * @param key
     */
    public void del(String...key){
        if (key != null && key.length > 0){
            if (key.length == 1){
                this.redisTemplate.delete(key[0]);
            }else {
                this.redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 根据key获取缓存
     * @param key
     * @return
     */
    public Object get(String key){
        return key == null ? null : this.redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通存入缓存数据
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value){
        try{
            this.redisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 普通存入缓存,并设置时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key, Object value, long time){
        try{
            if (time > 0L)
                this.redisTemplate.opsForValue().set(key,value, time, TimeUnit.SECONDS);
            else
                this.set(key,value);
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 递增
     * @param key
     * @param delta
     * @return
     */
    public long incr(String key, long delta){
        if (delta < 0L){
            throw new RuntimeException("递增因子必须大于0");
        }else
            return this.redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     * @param key
     * @param delta
     * @return
     */
    public long decr(String key, long delta){
        if (delta < 0L){
            throw new RuntimeException("递增因子必须大于0");
        }else
            return this.redisTemplate.opsForValue().increment(key, -delta);
    }

    /**
     * hashget
     * @param key
     * @param item
     * @return
     */
    public Object hget(String key, String item){
        return this.redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashkey对应的所有键值
     * @param key
     * @return
     */
    public Map<Object, Object> hmget(String key){
        return this.redisTemplate.opsForHash().entries(key);
    }

    /**
     * hashset
     * @param key
     * @param map
     * @return
     */
    public boolean hmset(String key, Map<String, Object> map){
        try {
            this.redisTemplate.opsForHash().putAll(key, map);
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * hashset 并设置时间
     * @param key
     * @param map
     * @param time
     * @return
     */
    public boolean hmset(String key, Map<String, Object> map, long time){
        try {
            this.redisTemplate.opsForHash().putAll(key, map);
            if (time > 0L){
                this.expire(key, time);
            }
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 向一张表中放入数据,如果不存在就创建
     * @param key
     * @param item
     * @param value
     * @return
     */
    public boolean hset(String key, String item, Object value){
        try{
            this.redisTemplate.opsForHash().put(key, item, value);
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key
     * @param item
     * @param value
     * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return
     */
    public boolean hset(String key, String item, Object value, long time){
        try{
            this.redisTemplate.opsForHash().put(key, item, value);
            if (time > 0L)
                this.expire(key, time);
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 删除hash表中的值
     * @param key
     * @param item
     */
    public void hdel(String key, Object...item){
        this.redisTemplate.opsForHash().delete(key,item);
    }

    /**
     * 判断hash表里是否有改key值
     * @param key
     * @param item
     * @return
     */
    public boolean hHasKey(String key, String item){
        return this.redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增,如果不存在就会创建一个,并把新增的值返回
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double hincr(String key, String item, double by){
        return this.redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减,如果不存在就会创建一个,并把减少的值返回
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double hdecr(String key, String item, double by){
        return this.redisTemplate.opsForHash().increment(key, item, -by);
    }

    /**
     * 根据key获取set中的所有值
     * @param key
     * @return
     */
    public Set<Object> sGet(String key){
        try {
            return this.redisTemplate.opsForSet().members(key);
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    /**
     * 根据value从一个set中查询是否存在
     * @param key
     * @param value
     * @return
     */
    public boolean sHasKey(String key, Object value){
        try{
            return this.redisTemplate.opsForSet().isMember(key, value);
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 将set数据放入缓存
     * @param key
     * @param values
     * @return
     */
    public long sSet(String key, Object... values){
        try {
            return this.redisTemplate.opsForSet().add(key,values);
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return 0L;
        }
    }

    /**
     * 将set数据放入缓存
     * @param key
     * @param values
     * @return
     */
    public long sSetAndTime(String key, long time, Object... values){
        try{
            Long count = this.redisTemplate.opsForSet().add(key, values);
            if (time > 0L){
                this.expire(key, time);
            }
            return count;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return 0L;
        }
    }

    /**
     * 获取set缓存数据的长度
     * @param key
     * @return
     */
    public long sGetSetSize(String key){
        try {
            return this.redisTemplate.opsForSet().size(key);
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return 0L;
        }
    }

    /**
     * 获取list缓存的内容
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List<Object> lGet(String key, long start, long end){
        try{
            return this.redisTemplate.opsForList().range(key, start, end);
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key
     * @return
     */
    public long lGetListSize(String key){
        try {
            return this.redisTemplate.opsForList().size(key);
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return 0L;
        }
    }

    /**
     * 通过索引 获取list缓存中的值
     * @param key
     * @param index
     * @return
     */
    public Object lGetIndex(String key, long index){
        try {
            return this.redisTemplate.opsForList().index(key, index);
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return 0L;
        }
    }

    /**
     * 将list放入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, Object value){
        try {
            this.redisTemplate.opsForList().rightPush(key, value);
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }
    public boolean lSet(String key, Object value, long time){
        try {
            this.redisTemplate.opsForList().rightPush(key, value);
            if (time > 0L){
                this.expire(key, time);
            }
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }
    public boolean lSet(String key,List<Object> value){
        try {
            this.redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }
    public boolean lSet(String key, List<Object> value, long time){
        try {
            this.redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0L){
                this.expire(key, time);
            }
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 根据索引 修改list缓存中的某个数据
     * @param key
     * @param index
     * @param value
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value){
        try {
            this.redisTemplate.opsForList().set(key, index, value);
            return true;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 移除n个值为value
     * @param key
     * @param count
     * @param value
     * @return
     */
    public long lRemove(String key, long count, Object value){
        try {
            Long remove = this.redisTemplate.opsForList().remove(key, count, value);
            return remove;
        }catch (Exception e){
            this.logger.error(ExceptionUtils.getStackTrace(e));
            return 0L;
        }
    }
}

  

posted @ 2019-08-30 17:21  小菜鸡的梦想  阅读(2895)  评论(0编辑  收藏  举报