springboot项目中redis配置

1 redis如何配置能支持批量模糊删除?

参数配置 :

#redis的ip地址
spring.redis.host=127.0.0.1
#端口
spring.redis.port=6379
#链接密码 如果redis没有设置密码则可以不填
spring.redis.password=
spring.redis.timeout=10000
#配置redis线程池
spring.redis.jedis.pool.maxActive=8
spring.redis.jedis.pool.maxIdle=8
spring.redis.jedis.pool.maxWait=-1
spring.redis.jedis.pool.minIdle=0

一般redis配置类 考虑扩展性 则一般会

	//这种配置支持redis的多种数据结构 string , list ,set ,hash等结构的存储 
	//但是这种配置经过测试不能实现string类型的模糊查询 
 	@Bean
    public RedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate template = new RedisTemplate ();
        template.setConnectionFactory(jedisConnectionFactory);
        return template;
    }

如果要实现string类型的key支持模糊查询则需要改为

 	@Bean
    public StringRedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        StringRedisTemplate  template = new StringRedisTemplate();
        template.setConnectionFactory(jedisConnectionFactory);
        return template;
    }

redis工具类模糊删除,查询写法

 public boolean delBatch(String pattern) {
        try {
        	//模糊查询出以pattern开头的所有key  * 为全匹配 和mysql中模糊查询中的'%'一样
            Set<String> keys = redisTemplate.keys(pattern + "*");
            //此处为遍历删除所有的查询出的键值对
            //如果需要查询则也是一样
            keys.forEach(keyStr -> {
                redisTemplate.delete(keyStr);
            });
            LOGGER.info("redis delete success.data : keys pattern ={},size = {}", pattern, keys.size());
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "removes the keys.", e.getClass().getSimpleName(), e);
            return false;
        }
        return true;
    }

完整配置

package com.track.able.redis;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * TODO redis配置
 *
 * @ClassName RedisConfig
 * @Description TODO
 * @Author tang mi
 * @Date 2019/9/26 11:12
 * @Version 1.0
 **/
@Component
@RefreshScope
public class RedisConfig extends CachingConfigurerSupport {
    public static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);


    @Autowired
    public RedisPoolConfig redisPoolConfig;

    public String host;

    public int port;

    public String password;

    public int timeout;

    @Bean
    @RefreshScope
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(redisPoolConfig.getMaxActive());
        config.setMaxWaitMillis(redisPoolConfig.getMaxWait());
        config.setMaxIdle(redisPoolConfig.getMaxIdle());
        config.setMinIdle(redisPoolConfig.getMinIdle());
        return config;
    }

    @Bean
    @RefreshScope
    public JedisPool jedisPool() {
        JedisPoolConfig config = getRedisConfig();
        JedisPool pool = new JedisPool(config, host, port, timeout, password);
        logger.info("init JredisPool ...");
        return pool;
    }

    @Bean
    @RefreshScope//表示阿里配置中心自动刷新注解,如果没有引入阿里配置中心 则删除该注解即可,不影响配置
    @Primary//指定默认初始化该工厂
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        //jedis工厂
        JedisConnectionFactory factory = new JedisConnectionFactory(jedisPoolConfig);
        //连接池配置
        factory.setHostName(host);
        factory.setPort(port);
        factory.setPassword(password);
        factory.setTimeout(timeout);
        factory.afterPropertiesSet();
        logger.info("JedisConnectionFactory bean init success.");
        return factory;
    }

    /**
     * @return org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>
     * @description: redis template config
     * @author lijun.tan
     * @eamil tlj@htrfid.com
     * @date 2018/6/25 12:04
     */
    @Bean
    @RefreshScope
    public StringRedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        StringRedisTemplate  template = new StringRedisTemplate();
        template.setConnectionFactory(jedisConnectionFactory);
        return template;
    }

	//注意:读取配置文件中的配置 大括号中的路径与你配置文件中配置一一对应 
    @Value("${spring.redis.host}")
    public void setHost(String host) {
        this.host = host;
    }

    @Value("${spring.redis.port}")
    public void setPort(int port) {
        this.port = port;
    }

    @Value("${spring.redis.password}")
    public void setPassword(String password) {
        this.password = password;
    }

    @Value("${spring.redis.timeout}")
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public String getPassword() {
        return password;
    }

    public int getTimeout() {
        return timeout;
    }
}

redis工具类

package com.track.able.redis;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * TODO
 *
 * @ClassName RedisUtils
 * @Description TODO
 * @Author tang mi
 * @Date 2019/10/30 20:52
 * @Version 1.0
 **/
@Component
public class RedisUtils {
    public static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RedisUtils.class);


    public static final String REDIS_ALIVE_FLAG = "PONG";

    public static final String ERROR_THROUGH = "Exception encountered when trying {} through {}. MSG is {}";
	//这里注入与本文的RedisConfig.redisTemplate方法的返回值一致
    @Autowired
    public StringRedisTemplate redisTemplate;

    /**
     * Set key to hold the string value.
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            LOGGER.info("redis set String success.data : {}={}", key, value);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "set key to hold the string value.", e.getClass().getSimpleName(), e);
            return false;
        }
        return true;
    }

    /**
     * @param key     key
     * @param value   设置的值
     * @param timeout 设置过期的时间
     * @param unit    时间单位。不能为空
     * @return boolean
     * @description: take string save to redis
     * @author lijun.tan
     * @eamil tlj@htrfid.com
     * @date 2018/6/12 18:04
     */
    public boolean set(String key, String value, long timeout, TimeUnit unit) {
        try {
            redisTemplate.opsForValue().set(key, value, timeout, unit);
            LOGGER.info("redis set String success.data : {}={}", key, value);
            return true;
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "set key to hold the string value.", e.getClass().getSimpleName(), e);
            return false;
        }
    }

    /**
     * Get the value of key.
     *
     * @param key
     * @return
     */
    public String get(String key) {
        String value = null;
        try {
            value = (String) redisTemplate.opsForValue().get(key);
            LOGGER.info("redis get the value of the key success,the key is {}", key);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "get the value of the key.", e.getClass().getSimpleName(), e);
        }
        return value;
    }

    /**
     * @param obj
     * @return T
     * @description: Get the value of key.
     * @author lijun.tan
     * @eamil tlj@htrfid.com
     * @date 2018/6/12 18:49
     */
    public <T> T get(Object obj) {
        T value = null;
        try {
            value = (T) redisTemplate.opsForValue().get(obj);
            LOGGER.info("redis get the value of the key success,the key is {}", obj);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "get the value of the key.", e.getClass().getSimpleName(), e);
        }
        return value;
    }

    /**
     * Removes the specified keys
     *
     * @param key
     * @return
     */
    public boolean del(String key) {
        try {
            redisTemplate.delete(key);
            LOGGER.info("redis delete success.data : key={}", key);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "removes the keys.", e.getClass().getSimpleName(), e);
            return false;
        }
        return true;

    }


    public boolean delBatch(String pattern) {
        try {
            Set<String> keys = redisTemplate.keys(pattern + "*");
            keys.forEach(keyStr -> {
                redisTemplate.delete(keyStr);
            });
            LOGGER.info("redis delete success.data : keys pattern ={},size = {}", pattern, keys.size());
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "removes the keys.", e.getClass().getSimpleName(), e);
            return false;
        }
        return true;

    }

    /**
     * Returns the value associated with field in the hash stored at key.
     *
     * @param key
     * @param field
     * @return
     */
    public String hGet(String key, String field) {
        String value = null;
        try {
            value = (String) redisTemplate.opsForHash().get(key, field);
            LOGGER.info("redis get the value with the field in the hash stored at the key success,the key is {}, the field is {}", key, field);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "get the value with the field in the hash stored at the key.", e.getClass().getSimpleName(), e);
        }
        return value;
    }

    /**
     * Returns all fields and values of the hash stored at key.
     *
     * @param key
     * @return
     */
    public Map<Object, Object> hGetAll(String key) {
        try {
            Map<Object, Object> map = redisTemplate.opsForHash().entries(key);
            if (map == null) {
                map = new HashMap<>(16);
            }
            return map;
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "get values of the hash stored at key, key=" + key + ".", e.getClass().getSimpleName(), e);
            return null;
        }

    }

    /**
     * Sets field in the hash stored at key to value.
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public void hSet(String key, String field, String value) {
        try {
            redisTemplate.opsForHash().put(key, field, value);
            LOGGER.info("set the hash set success with key = {}, field = {}, value = {}", key, field, value);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "set the hash set.", e.getClass().getSimpleName(), e);
        }

    }

    /**
     * Sets the specified fields to their respective values in the hash stored at key.
     *
     * @param key
     * @param map
     * @return
     */
    public boolean hmSet(String key, Map<Object, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            StringBuffer buffer = new StringBuffer();
            buffer.append("[");
            for (Object str : map.keySet()) {
                buffer.append(str + "," + map.get(str) + ";");
            }
            buffer.append("]");
            LOGGER.info("redis set  mSet success.data key = {},value ={}", key, buffer);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "set key to hold the map value.", e.getClass().getSimpleName(), e.getMessage());
            return false;
        }
        return true;
    }


    /**
     * Returns the specified elements of the list stored at key.
     *
     * @param key
     * @return
     */
    public List<?> getList(String key) {
        List<?> list = null;
        try {
            list = redisTemplate.opsForList().range(key, 0, -1);
            LOGGER.info("get the list with the key success. key is {}", key);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "get the list.", e.getClass().getSimpleName(), e);
        }
        return list;
    }

    /**
     * Returns all the members of the set value stored at key.
     *
     * @param key
     */
    public Set<?> getSet(String key) {
        Set<?> set = null;
        try {
            set = redisTemplate.opsForSet().members(key);
            LOGGER.info("get the set with the key success. key is {}", key);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "get the set.", e.getClass().getSimpleName(), e);
        }
        return set;
    }


    /**
     * 根据提供的key集合按顺序获取对应的value值
     *
     * @param keys 集合不能为null 可以为empty 集合
     */
    public List<?> multiGet(Collection<String> keys) {
        List<?> list = null;
        try {
            list = redisTemplate.opsForValue().multiGet(keys);
            LOGGER.info("get the list with the key success. key is {}", keys);
        } catch (RedisConnectionFailureException e) {
            LOGGER.error(ERROR_THROUGH, "get the list.", e.getClass().getSimpleName(), e);
        }
        return list;
    }

    /**
     * Returns true if redis is running.
     *
     * @return
     */
    public boolean ping() {
        boolean flag = false;
        RedisConnection connection = null;
        try {
            connection = redisTemplate.getConnectionFactory().getConnection();
        } catch (Exception e) {
            LOGGER.error(ERROR_THROUGH, "connect with redis controller", e.getClass().getSimpleName(), e);
        }
        if (connection != null) {
            String result = "";
            try {
                result = connection.ping();
            } catch (Exception e) {
                LOGGER.error(ERROR_THROUGH, "test if a connection is still alive", e.getClass().getSimpleName(), e);
            }
            if (REDIS_ALIVE_FLAG.equalsIgnoreCase(result)) {
                flag = true;
            }
            connection.close();
        }
        return flag;
    }

    /**
     * Returns all keys matching pattern
     *
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern) {
        if (ping()) {
            return redisTemplate.keys(pattern);
        }
        return null;
    }

    /**
     * Check key exist or not exist
     *
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * @param
     * @return
     * @description:TODO
     * @author jianhua.hong
     * @eamil hjh@htrfid.com
     * @date 2018/6/28 16:45
     */
    public Long autoIncrement(String key, long value) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long num = redisAtomicLong.addAndGet(value);
        return num;

    }


}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值