Redis 工具类

发布于 2020-07-09  689 次阅读


/**
  redis:
    # Redis服务器连接端口
    port: 6379
    database: 1 # 用第几号库
    # Redis服务器地址
    host: xx.xx.xx.xx
    # Redis服务器连接密码(默认为空)
    password: 123456
    jedis:
      pool:
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 20
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: 10000
        # 连接池中的最大空闲连接
        max-idle: 10
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接超时时间(毫秒)
    timeout: 5000
*/

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 *  jedis 连接池配置类
 * @author yaoguanquan
 * @creote 2020-05-31-16:57
 */
@Configuration
@EnableCaching
@Slf4j
public class RedisConfiguration extends CachingConfigurerSupport {

    /**
     * SpringSession  需要注意的就是redis需要2.8以上版本,然后开启事件通知,在redis配置文件里面加上
     * notify-keyspace-events Ex
     * Keyspace notifications功能默认是关闭的(默认地,Keyspace 时间通知功能是禁用的,因为它或多或少会使用一些CPU的资源)。
     * 或是使用如下命令:
     * redis-cli config set notify-keyspace-events Egx
     * 如果你的Redis不是你自己维护的,比如你是使用阿里云的Redis数据库,你不能够更改它的配置,那么可以使用如下方法:在applicationContext.xml中配置
     * <util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
     * @return
     */

    @Value("${spring.redis.database}")
    private int index;
    @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;

    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;




    /**
     * RedisTemplate配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        //定义key序列化方式
        //RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型会出现异常信息;需要我们上面的自定义key生成策略,一般没必要
        //定义value的序列化方式
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }


    @Bean
    public JedisPool redisPoolFactory(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setMaxTotal(maxActive);
        jedisPoolConfig.setMinIdle(minIdle);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,host,port,timeout,password,index);

        log.info("JedisPool is start! !");
        log.info("redis location is :" + host + ": " + port + " ,database is :" + index);
        return  jedisPool;
    }
}
import cn.ustyle.server.biz.config.RedisConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Random;

/**
 * <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
 * <dependency>
 *     <groupId>redis.clients</groupId>
 *     <artifactId>jedis</artifactId>
 *     <version>3.3.0</version>
 * </dependency>
 *
 * @author yaoguanquan
 * @creote 2020-05-31-16:57
 */
@Component
@Slf4j
public class RedisClient<T> {

    @Resource
    private RedisConfiguration jedisConfig;

    public synchronized void set(String key,String value,Integer hour) throws Exception{

        Jedis jedis = null;
        try {
            JedisPool jedisPool= jedisConfig.redisPoolFactory();
            jedis = jedisPool.getResource();
            Pipeline pipeline = jedis.pipelined();
            if(StringUtils.isEmpty(key) || StringUtils.isEmpty(value)){
                throw new Exception("key or value is null");
            }
            pipeline.set(key,value);
            // 修改为 ? 小时后删除
            pipeline.expire(key, randomHour(hour));
            pipeline.sync(); //执行管道中的命令
        }finally {
            if(jedisConfig.redisPoolFactory() != null){
                // 返还到连接池
                jedis.close();
            }
        }
    }

    public void setMinute(String key, String value, Integer minute)throws Exception {

        Jedis jedis = null;
        try {
            JedisPool jedisPool= jedisConfig.redisPoolFactory();
            jedis = jedisPool.getResource();
            if(StringUtils.isEmpty(key) || StringUtils.isEmpty(value)){
                throw new Exception("key or value is null");
            }
            Pipeline pipelined = jedis.pipelined();
            pipelined.set(key,value);
            // 修改为 ? 分钟后删除
            pipelined.expire(key, randomMinute(minute));
            pipelined.sync(); //执行管道中的命令
        }finally {
            if(jedisConfig.redisPoolFactory() != null){
                // 返还到连接池
                jedis.close();
            }
        }
    }

    public String get(String key) throws Exception{
        Jedis jedis = null;
        try {
            JedisPool jedisPool= jedisConfig.redisPoolFactory();
            jedis = jedisPool.getResource();
            Pipeline pipelined = jedis.pipelined();
            Response<String> stringResponse = pipelined.get(key);
            pipelined.sync(); //执行管道中的命令
            return stringResponse.get();
        }finally {
            if(jedisConfig.redisPoolFactory() != null){
                // 返还到连接池
                jedis.close();
            }
        }
    }

    public synchronized Boolean delete(String key) throws Exception{
        Jedis jedis = null;
        try {
            JedisPool jedisPool= jedisConfig.redisPoolFactory();
            jedis = jedisPool.getResource();
            if(jedis.del(key) == 1){
                return true;
            }
            return false;
        }finally {
            if(jedisConfig.redisPoolFactory() != null){
                // 返还到连接池
                jedis.close();
            }
        }
    }

    /**
     *
     * @param keyPattern
     * @return
     * @throws Exception
     */

    public List<String> like(String keyPattern) throws Exception{
        Jedis jedis = null;
        try{
            JedisPool jedisPool= jedisConfig.redisPoolFactory();
            jedis = jedisPool.getResource();
            Pipeline pipelined = jedis.pipelined();
            Response<Set<String>> response = pipelined.keys(keyPattern);
            pipelined.sync();//执行管道中的命令
            Set<String> keys = response.get();
            List<String> keyList = new LinkedList<>();
            for(String key : keys){
                String s = jedis.get(key);
                keyList.add(s);
            }
            return keyList;
        }finally {
            if(jedisConfig.redisPoolFactory() != null){
                // 返还到连接池
                jedis.close();
            }
        }
    }

    public Map<String, String> queryKey(String key) throws Exception{
        Jedis jedis = null;
        try{
            String keyPattern = "*" + key + "*";
            Map<String, String> res = new HashMap<String, String>();
            JedisPool jedisPool= jedisConfig.redisPoolFactory();
            jedis = jedisPool.getResource();
            Pipeline pipelined = jedis.pipelined();
            Response<Set<String>> keys1 = pipelined.keys(keyPattern);
            pipelined.sync(); //执行管道中的命令
            Set<String> keys = keys1.get();
            for (String keyTmp : keys) {

                String keyType = jedis.type(keyTmp);
                if (keyType.equals("none")) {
                } else if (keyType.equals("list")) {
                    res.put(keyTmp, JSONObject.toJSONString(jedis.lrange(keyTmp, 0, -1)));
                } else if (keyType.equals("set")) {
                    res.put(keyTmp, JSONObject.toJSONString(jedis.smembers(keyTmp)));
                } else if (keyType.equals("string")) {
                    res.put(keyTmp, jedis.get(keyTmp));
                } else if (keyType.equals("zset")) {
                    res.put(keyTmp, JSONObject.toJSONString(jedis.zrange(keyTmp, 0, -1)));
                } else if (keyType.equals("hash")) {
                    res.put(keyTmp, JSONObject.toJSONString(jedis.hgetAll(keyTmp)));
                }
            }
            return res;
        }finally {
            if(jedisConfig.redisPoolFactory() != null){
                // 返还到连接池
                jedis.close();
            }
        }

    }



    /**
     * 返回对应小时
     * @param hour 小时
     * @return
     */
    public static Integer randomHour(Integer hour){
        return  60 * 60 * hour;
    }

    /**
     * 返回对应小时
     * @param minute 小时
     * @return
     */
    public static Integer randomMinute(Integer minute){
        return  60 * minute;
    }


//    public static void main(String[] args) {
//        Jedis jedis = null;
//        JedisPool jedisPool = new JedisPool(new GenericObjectPoolConfig(),"xxxx",6379,20000,"123456");
//        try {
//            jedis = jedisPool.getResource();
////            jedis.set("rrr","昆明靠哦入关");
//            jedis.get("rrr");
//            System.out.println(jedis.get("rrr"));
//        } catch (Exception e){
//            e.printStackTrace();
//        } finally {
//            jedis.close();
//        }
//
//    }

}

公交车司机终于在众人的指责中将座位让给了老太太