Redis和SpringBoot整合RedisUtils類

1、引入依賴

<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>

  

2、在application.yml 配置redis服務器

項目沒完成,配置不在子項目中java

 

 

3、寫一個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;
    }

}

  

4、編寫一個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;
        }
    }
}
相關文章
相關標籤/搜索