美文网首页我爱编程
spring boot实际应用(五) redis

spring boot实际应用(五) redis

作者: 架构技术专栏 | 来源:发表于2017-08-30 18:30 被阅读209次

redis是一个目前非常流行的缓存数据库,具体技术细节这里就不做描述了,下面说下干货,怎么实际应用

目前项目都使用spring boot来实现了,SO 我也来点新鲜的,说实话确实好使。

先说下使用的依赖

<dependencies>  
    <dependency>  
          <groupId>org.springframework.boot</groupId>  
         <artifactId>spring-boot-starter-data-redis</artifactId>  
    </dependency>  
    <dependency>  
          <groupId>com.alibaba</groupId>  
          <artifactId>fastjson</artifactId>  
    </dependency>  
    <dependency>  
          <groupId>org.springframework.boot</groupId>  
         <artifactId>spring-boot-configuration-processor</artifactId>  
          <optional>true</optional>  
    </dependency>  
 </dependencies>  

1、基本配置,这个不管用配置文件还是config都少不了的,在这里我学习了spring boot的特性,。就是做了个底层包,在公司项目只要加载了这个包就默认启动redis。
目前redis 有sentinel cluster两种模式,下面贴代码

sentinel配置类

package com.ecej.nove.redis.config;  
  
import java.util.HashSet;  
  
import javax.annotation.Resource;  
  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;  
import org.springframework.boot.context.properties.EnableConfigurationProperties;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.data.redis.connection.RedisSentinelConfiguration;  
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
import org.springframework.data.redis.core.RedisTemplate;  
import org.springframework.data.redis.serializer.StringRedisSerializer;  
import org.springframework.util.StringUtils;  
  
import redis.clients.jedis.JedisPoolConfig;  
  
/** 
 *  
 * @author QIANG 
 * 
 */  
@Configuration  
@EnableConfigurationProperties(EcejRedisProperties.class)  
@ConditionalOnProperty(name = "ecej.redis.sentinel")  
public class RedisSentinelConfig {  
    private Logger LOG = LoggerFactory.getLogger(RedisSentinelConfig.class);  
  
    @Resource  
    private EcejRedisProperties redisProperties;  
  
    public JedisPoolConfig jedisPoolConfig() {  
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();  
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());  
        jedisPoolConfig.setMaxTotal(redisProperties.getMaxTotal());  
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWaitMillis());  
        return jedisPoolConfig;  
  
    }  
  
    public RedisSentinelConfiguration jedisSentinelConfig() {  
        String[] hosts = redisProperties.getHostName().split(",");  
        HashSet<String> sentinelHostAndPorts = new HashSet<>();  
        for (String hn : hosts) {  
            sentinelHostAndPorts.add(hn);  
        }  
        return new RedisSentinelConfiguration(redisProperties.getMastername(), sentinelHostAndPorts);  
  
    }  
  
    @Bean  
    public JedisConnectionFactory jedisConnectionFactory() {  
  
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisSentinelConfig(),  
                jedisPoolConfig());  
        if (!StringUtils.isEmpty(redisProperties.getPassword()))  
            jedisConnectionFactory.setPassword(redisProperties.getPassword());  
        return jedisConnectionFactory;  
    }  
  
    @Bean  
    public RedisTemplate<String, String> redisTemplate() {  
  
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();  
        redisTemplate.setConnectionFactory(jedisConnectionFactory());  
        redisTemplate.setDefaultSerializer(new StringRedisSerializer());  
        LOG.info("create redisTemplate success");  
        return redisTemplate;  
    }  
  
}  

下面贴出cluster配置

package com.ecej.nove.redis.config;  
  
import java.util.HashSet;  
import java.util.Set;  
  
import javax.annotation.Resource;  
  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;  
import org.springframework.boot.context.properties.EnableConfigurationProperties;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.data.redis.connection.RedisClusterConfiguration;  
import org.springframework.data.redis.connection.RedisClusterNode;  
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.StringRedisSerializer;  
import org.springframework.util.StringUtils;  
  
import redis.clients.jedis.JedisPoolConfig;  
  
/** 
 *  
 * @author QIANG 
 * 
 */  
@Configuration  
@EnableConfigurationProperties(EcejRedisProperties.class)  
@ConditionalOnProperty(name = "ecej.redis.cluster")  
public class RedisClusterConfig {  
    private Logger LOG = LoggerFactory.getLogger(RedisClusterConfig.class);  
  
    @Resource  
    private EcejRedisProperties redisProperties;  
  
    public JedisPoolConfig jedisPoolConfig() {  
  
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();  
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());  
        jedisPoolConfig.setMaxTotal(redisProperties.getMaxTotal());  
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWaitMillis());  
        return jedisPoolConfig;  
  
    }  
  
    public RedisClusterConfiguration redisClusterConfiguration() {  
  
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();  
        String[] hosts = redisProperties.getHostName().split(":");  
        Set<RedisNode> redisNodes = new HashSet<>();  
        redisNodes.add(new RedisClusterNode(hosts[0], Integer.valueOf(hosts[1])));  
        redisClusterConfiguration.setClusterNodes(redisNodes);  
        redisClusterConfiguration.setMaxRedirects(redisProperties.getMaxRedirects());  
        return redisClusterConfiguration;  
  
    }  
  
    @Bean  
    public JedisConnectionFactory jedisConnectionFactory() {  
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration(),  
                jedisPoolConfig());  
        if (!StringUtils.isEmpty(redisProperties.getPassword()))  
            jedisConnectionFactory.setPassword(redisProperties.getPassword());  
        return jedisConnectionFactory;  
    }  
  
    @Bean  
    public RedisTemplate<String, String> redisTemplate() {  
  
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();  
        redisTemplate.setConnectionFactory(jedisConnectionFactory());  
        redisTemplate.setDefaultSerializer(new StringRedisSerializer());  
        LOG.info("create RedisTemplate success");  
        return redisTemplate;  
    }  
}  
  

使用的配置类,用于加载参数

package com.ecej.nove.redis.config;  

import org.springframework.boot.context.properties.ConfigurationProperties;  

/** 
* 
* @author QIANG 
* 
*/  
@ConfigurationProperties(prefix = "ecej.redis")  
public class EcejRedisProperties {  

   /** 
    * Max number of "idle" connections in the pool. Use a negative value to 
    * indicate an unlimited number of idle connections. 
    */  
   private int maxIdle = 10;  

   /** 
    * 最大连接数 
    */  
   private int maxTotal = 500;  

   private int maxWaitMillis = 3000;  

   private String hostName = "localhost";  

   private String password;  

   /** 
    * Maximum number of redirects to follow when executing commands across the 
    * cluster. 
    */  
   private int maxRedirects = 10;  

   private String mastername;  

   public int getMaxIdle() {  
         return maxIdle;  
   }  

   public void setMaxIdle(int maxIdle) {  
         this.maxIdle = maxIdle;  
   }  

   public int getMaxTotal() {  
         return maxTotal;  
   }  

   public void setMaxTotal(int maxTotal) {  
         this.maxTotal = maxTotal;  
   }  

   public int getMaxWaitMillis() {  
         return maxWaitMillis;  
   }  

   public void setMaxWaitMillis(int maxWaitMillis) {  
         this.maxWaitMillis = maxWaitMillis;  
   }  

   public String getHostName() {  
         return hostName;  
   }  

   public void setHostName(String hostName) {  
         this.hostName = hostName;  
   }  

   public String getPassword() {  
         return password;  
   }  

   public void setPassword(String password) {  
         this.password = password;  
   }  

   public int getMaxRedirects() {  
         return maxRedirects;  
   }  

   public void setMaxRedirects(int maxRedirects) {  
         this.maxRedirects = maxRedirects;  
   }  

   public String getMastername() {  
         return mastername;  
   }  

   public void setMastername(String mastername) {  
         this.mastername = mastername;  
   }  

}  

怎么使用呢,下面编写了使用的快捷方法

package com.ecej.nove.redis.utils;  
  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import java.util.Set;  
import java.util.concurrent.TimeUnit;  
  
import javax.annotation.PostConstruct;  
import javax.annotation.Resource;  
  
import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;  
import org.springframework.data.redis.core.ListOperations;  
import org.springframework.data.redis.core.RedisCallback;  
import org.springframework.data.redis.core.RedisTemplate;  
import org.springframework.data.redis.core.SetOperations;  
import org.springframework.data.redis.core.ValueOperations;  
  
import com.alibaba.fastjson.JSON;  
import com.alibaba.fastjson.parser.Feature;  
  
/** 
 * 
 * @author QIANG 
 * 
 */  
public class JedisClusterUtils {  
  
    @Resource  
    private RedisTemplate<String, String> redisTemplate;  
  
    private static JedisClusterUtils cacheUtils;  
  
    @PostConstruct  
    public void init() {  
        cacheUtils = this;  
        cacheUtils.redisTemplate = this.redisTemplate;  
    }  
  
    /** 
     * 将数据存入缓存 
     * 
     * @param key 
     * @param val 
     * @return 
     */  
    public static void saveString(String key, String val) {  
  
        ValueOperations<String, String> vo = cacheUtils.redisTemplate.opsForValue();  
        vo.set(key, val);  
    }  
  
    /** 
     * 将数据存入缓存的集合中 
     * 
     * @param key 
     * @param val 
     * @return 
     */  
    public static void saveToSet(String key, String val) {  
  
        SetOperations<String, String> so = cacheUtils.redisTemplate.opsForSet();  
  
        so.add(key, val);  
    }  
  
    /** 
     * 
     * 
     * @param key 
     *            缓存Key 
     * @return keyValue 
     * @author:mijp 
     * @since:2017/1/16 13:23 
     */  
    public static String getFromSet(String key) {  
        return cacheUtils.redisTemplate.opsForSet().pop(key);  
    }  
  
    /** 
     * 将 key的值保存为 value ,当且仅当 key 不存在。 若给定的 key 已经存在,则 SETNX 不做任何动作。 SETNX 是『SET 
     * if Not eXists』(如果不存在,则 SET)的简写。 <br> 
     * 保存成功,返回 true <br> 
     * 保存失败,返回 false 
     */  
    public static boolean saveNX(String key, String val) {  
  
        /** 设置成功,返回 1 设置失败,返回 0 **/  
        return cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
            return connection.setNX(key.getBytes(), val.getBytes());  
        });  
  
    }  
  
    /** 
     * 将 key的值保存为 value ,当且仅当 key 不存在。 若给定的 key 已经存在,则 SETNX 不做任何动作。 SETNX 是『SET 
     * if Not eXists』(如果不存在,则 SET)的简写。 <br> 
     * 保存成功,返回 true <br> 
     * 保存失败,返回 false 
     * 
     * @param key 
     * @param val 
     * @param expire 
     *            超时时间 
     * @return 保存成功,返回 true 否则返回 false 
     */  
    public static boolean saveNX(String key, String val, int expire) {  
  
        boolean ret = saveNX(key, val);  
        if (ret) {  
            cacheUtils.redisTemplate.expire(key, expire, TimeUnit.SECONDS);  
        }  
        return ret;  
    }  
  
    /** 
     * 将数据存入缓存(并设置失效时间) 
     * 
     * @param key 
     * @param val 
     * @param seconds 
     * @return 
     */  
    public static void saveString(String key, String val, int seconds) {  
  
        cacheUtils.redisTemplate.opsForValue().set(key, val, seconds, TimeUnit.SECONDS);  
    }  
  
    /** 
     * 将自增变量存入缓存 
     */  
    public static void saveSeq(String key, long seqNo) {  
  
        cacheUtils.redisTemplate.delete(key);  
        cacheUtils.redisTemplate.opsForValue().increment(key, seqNo);  
    }  
  
    /** 
     * 将递增浮点数存入缓存 
     */  
    public static void saveFloat(String key, float data) {  
  
        cacheUtils.redisTemplate.delete(key);  
        cacheUtils.redisTemplate.opsForValue().increment(key, data);  
    }  
  
    /** 
     * 保存复杂类型数据到缓存 
     * 
     * @param key 
     * @param obj 
     * @return 
     */  
    public static void saveBean(String key, Object obj) {  
  
        cacheUtils.redisTemplate.opsForValue().set(key, JSON.toJSONString(obj));  
    }  
  
    /** 
     * 保存复杂类型数据到缓存(并设置失效时间) 
     * 
     * @param key 
     * @param Object 
     * @param seconds 
     * @return 
     */  
    public static void saveBean(String key, Object obj, int seconds) {  
  
        cacheUtils.redisTemplate.opsForValue().set(key, JSON.toJSONString(obj), seconds, TimeUnit.SECONDS);  
    }  
  
    /** 
     * 功能: 存到指定的队列中<br /> 
     * 左近右出<br\> 作者: 耿建委 
     * 
     * @param key 
     * @param val 
     * @param size 
     *            队列大小限制 0:不限制 
     */  
    public static void saveToQueue(String key, String val, long size) {  
  
        ListOperations<String, String> lo = cacheUtils.redisTemplate.opsForList();  
  
        if (size > 0 && lo.size(key) >= size) {  
            lo.rightPop(key);  
        }  
        lo.leftPush(key, val);  
    }  
  
    /** 
     * 保存到hash集合中 
     * 
     * @param hName 
     *            集合名 
     * @param key 
     * @param val 
     */  
    public static void hashSet(String hName, String key, String value) {  
  
        cacheUtils.redisTemplate.opsForHash().put(hName, key, value);  
    }  
  
    /** 
     * 根据key获取所以值 
     *  
     * @param key 
     * @return 
     */  
    public static Map<Object, Object> hgetAll(String key) {  
  
        return cacheUtils.redisTemplate.opsForHash().entries(key);  
    }  
  
    /** 
     * 保存到hash集合中 
     * 
     * @param <T> 
     * 
     * @param hName 
     *            集合名 
     * @param key 
     * @param val 
     */  
    public static <T> void hashSet(String hName, String key, T t) {  
  
        hashSet(hName, key, JSON.toJSONString(t));  
    }  
  
    /** 
     * 取得复杂类型数据 
     * 
     * @param key 
     * @param obj 
     * @param clazz 
     * @return 
     */  
    public static <T> T getBean(String key, Class<T> clazz) {  
  
        String value = cacheUtils.redisTemplate.opsForValue().get(key);  
        if (value == null) {  
            return null;  
        }  
        return JSON.parseObject(value, clazz);  
    }  
  
    /** 
     * 从缓存中取得字符串数据 
     * 
     * @param key 
     * @return 数据 
     */  
    public static String getString(String key) {  
        cacheUtils.redisTemplate.opsForValue().get(key);  
  
        return cacheUtils.redisTemplate.opsForValue().get(key);  
    }  
  
    /** 
     * 
     * 功能: 从指定队列里取得数据<br /> 
     * 作者: 耿建委 
     * 
     * @param key 
     * @param size 
     *            数据长度 
     * @return 
     */  
    public static List<String> getFromQueue(String key, long size) {  
  
        boolean flag = cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
            return connection.exists(key.getBytes());  
        });  
  
        if (flag) {  
            return new ArrayList<>();  
        }  
        ListOperations<String, String> lo = cacheUtils.redisTemplate.opsForList();  
        if (size > 0) {  
            return lo.range(key, 0, size - 1);  
        } else {  
            return lo.range(key, 0, lo.size(key) - 1);  
        }  
    }  
  
    /** 
     * 
     * 功能: 从指定队列里取得数据<br /> 
     * 作者: 耿建委 
     * 
     * @param key 
     * @return 
     */  
    public static String popQueue(String key) {  
  
        return cacheUtils.redisTemplate.opsForList().rightPop(key);  
  
    }  
  
    /** 
     * 取得序列值的下一个 
     * 
     * @param key 
     * @return 
     */  
    public static Long getSeqNext(String key) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> {  
  
            return connection.incr(key.getBytes());  
  
        });  
    }  
  
    /** 
     * 取得序列值的下一个 
     * 
     * @param key 
     * @return 
     */  
    public static Long getSeqNext(String key, long value) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> {  
  
            return connection.incrBy(key.getBytes(), value);  
  
        });  
  
    }  
  
    /** 
     * 将序列值回退一个 
     * 
     * @param key 
     * @return 
     */  
    public static void getSeqBack(String key) {  
  
        cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> connection.decr(key.getBytes()));  
  
    }  
  
    /** 
     * 从hash集合里取得 
     * 
     * @param hName 
     * @param key 
     * @return 
     */  
    public static Object hashGet(String hName, String key) {  
  
        return cacheUtils.redisTemplate.opsForHash().get(hName, key);  
    }  
  
    public static <T> T hashGet(String hName, String key, Class<T> clazz) {  
  
        return JSON.parseObject((String) hashGet(hName, key), clazz);  
    }  
  
    /** 
     * 增加浮点数的值 
     * 
     * @param key 
     * @return 
     */  
    public static Double incrFloat(String key, double incrBy) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Double>) connection -> {  
  
            return connection.incrBy(key.getBytes(), incrBy);  
  
        });  
    }  
  
    /** 
     * 判断是否缓存了数据 
     * 
     * @param key 
     *            数据KEY 
     * @return 判断是否缓存了 
     */  
    public static boolean isCached(String key) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
            return connection.exists(key.getBytes());  
        });  
    }  
  
    /** 
     * 判断hash集合中是否缓存了数据 
     * 
     * @param hName 
     * @param key 
     *            数据KEY 
     * @return 判断是否缓存了 
     */  
    public static boolean hashCached(String hName, String key) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
            return connection.hExists(key.getBytes(), key.getBytes());  
        });  
    }  
  
    /** 
     * 判断是否缓存在指定的集合中 
     * 
     * @param key 
     *            数据KEY 
     * @param val 
     *            数据 
     * @return 判断是否缓存了 
     */  
    public static boolean isMember(String key, String val) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
            return connection.sIsMember(key.getBytes(), val.getBytes());  
        });  
    }  
  
    /** 
     * 从缓存中删除数据 
     * 
     * @param string 
     * @return 
     */  
    public static void delKey(String key) {  
  
        cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> connection.del(key.getBytes()));  
    }  
  
    /** 
     * 设置超时时间 
     * 
     * @param key 
     * @param seconds 
     */  
    public static void expire(String key, int seconds) {  
        cacheUtils.redisTemplate  
                .execute((RedisCallback<Boolean>) connection -> connection.expire(key.getBytes(), seconds));  
  
    }  
  
    /** 
     * 列出set中所有成员 
     * 
     * @param setName 
     *            set名 
     * @return 
     */  
    public static Set<Object> listSet(String setName) {  
  
        return cacheUtils.redisTemplate.opsForHash().keys(setName);  
  
    }  
  
    /** 
     * 向set中追加一个值 
     * 
     * @param setName 
     *            set名 
     * @param value 
     */  
    public static void setSave(String setName, String value) {  
  
        cacheUtils.redisTemplate  
                .execute((RedisCallback<Long>) connection -> connection.sAdd(setName.getBytes(), value.getBytes()));  
  
    }  
  
    /** 
     * 逆序列出sorted set包括分数的set列表 
     * 
     * @param key 
     *            set名 
     * @param start 
     *            开始位置 
     * @param end 
     *            结束位置 
     * @return 列表 
     */  
    public static Set<Tuple> listSortedsetRev(String key, int start, int end) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Set<Tuple>>) connection -> {  
            return connection.zRevRangeWithScores(key.getBytes(), start, end);  
        });  
    }  
  
    /** 
     * 逆序取得sorted sort排名 
     * 
     * @param key 
     *            set名 
     * @param member 
     *            成员名 
     * @return 排名 
     */  
    public static Long getRankRev(String key, String member) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> {  
            return connection.zRevRank(key.getBytes(), member.getBytes());  
        });  
  
    }  
  
    /** 
     * 根据成员名取得sorted sort分数 
     * 
     * @param key 
     *            set名 
     * @param member 
     *            成员名 
     * @return 分数 
     */  
    public static Double getMemberScore(String key, String member) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Double>) connection -> {  
            return connection.zScore(key.getBytes(), member.getBytes());  
        });  
    }  
  
    /** 
     * 向sorted set中追加一个值 
     * 
     * @param key 
     *            set名 
     * @param score 
     *            分数 
     * @param member 
     *            成员名称 
     */  
    public static void saveToSortedset(String key, Double score, String member) {  
  
        cacheUtils.redisTemplate.execute(  
                (RedisCallback<Boolean>) connection -> connection.zAdd(key.getBytes(), score, member.getBytes()));  
    }  
  
    /** 
     * 从sorted set删除一个值 
     * 
     * @param key 
     *            set名 
     * @param member 
     *            成员名称 
     */  
    public static void delFromSortedset(String key, String member) {  
        cacheUtils.redisTemplate  
                .execute((RedisCallback<Long>) connection -> connection.zRem(key.getBytes(), member.getBytes()));  
  
    }  
  
    /** 
     * 从hash map中取得复杂类型数据 
     * 
     * @param key 
     * @param field 
     * @param clazz 
     */  
    public static <T> T getBeanFromMap(String key, String field, Class<T> clazz) {  
  
        byte[] input = cacheUtils.redisTemplate.execute((RedisCallback<byte[]>) connection -> {  
            return connection.hGet(key.getBytes(), field.getBytes());  
        });  
        return JSON.parseObject(input, clazz, Feature.AutoCloseSource);  
    }  
  
    /** 
     * 从hashmap中删除一个值 
     * 
     * @param key 
     *            map名 
     * @param field 
     *            成员名称 
     */  
    public static void delFromMap(String key, String field) {  
  
        cacheUtils.redisTemplate  
                .execute((RedisCallback<Long>) connection -> connection.hDel(key.getBytes(), field.getBytes()));  
  
    }  
  
    /** 
     * 
     * @Description: 根据key增长 ,计数器 
     * @author clg 
     * @date 2016年6月30日 下午2:37:52 
     * 
     * @param key 
     * @return 
     */  
    public static long incr(String key) {  
  
        return cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> {  
            return connection.incr(key.getBytes());  
        });  
    }  
  
    /** 
     * 
     * @Description: 根据key获取当前计数结果 
     * @author clg 
     * @date 2016年6月30日 下午2:38:20 
     * 
     * @param key 
     * @return 
     */  
    public static String getCount(String key) {  
  
        return cacheUtils.redisTemplate.opsForValue().get(key);  
    }  
  
    /** 
     * 将所有指定的值插入到存于 key 的列表的头部。如果 key 不存在,那么在进行 push 操作前会创建一个空列表 
     * 
     * @param <T> 
     * 
     * @param key 
     * @param value 
     * @return 
     */  
    public static <T> Long lpush(String key, T value) {  
  
        return cacheUtils.redisTemplate.opsForList().leftPush(key, JSON.toJSONString(value));  
    }  
  
    /** 
     * 只有当 key 已经存在并且存着一个 list 的时候,在这个 key 下面的 list 的头部插入 value。 与 LPUSH 相反,当 
     * key 不存在的时候不会进行任何操作 
     * 
     * @param key 
     * @param value 
     * @return 
     */  
    public static <T> Long lpushx(String key, T value) {  
  
        return cacheUtils.redisTemplate.opsForList().leftPushIfPresent(key, JSON.toJSONString(value));  
    }  
  
    /** 
     * 返回存储在 key 里的list的长度。 如果 key 不存在,那么就被看作是空list,并且返回长度为 0 
     * 
     * @param key 
     * @return 
     */  
    public static Long llen(String key) {  
  
        return cacheUtils.redisTemplate.opsForList().size(key);  
    }  
  
    /** 
     * 返回存储在 key 的列表里指定范围内的元素。 start 和 end 
     * 偏移量都是基于0的下标,即list的第一个元素下标是0(list的表头),第二个元素下标是1,以此类推 
     * 
     * @param key 
     * @return 
     */  
    public static List<String> lrange(String key, long start, long end) {  
  
        return cacheUtils.redisTemplate.opsForList().range(key, start, end);  
    }  
  
    /** 
     * 移除并且返回 key 对应的 list 的第一个元素 
     * 
     * @param key 
     * @return 
     */  
    public static String lpop(String key) {  
  
        return cacheUtils.redisTemplate.opsForList().leftPop(key);  
    }  
  
    /** 
     * 保存到hash集合中 只在 key 指定的哈希集中不存在指定的字段时,设置字段的值。如果 key 指定的哈希集不存在,会创建一个新的哈希集并与 
     * key 关联。如果字段已存在,该操作无效果。 
     * 
     * @param hName 
     *            集合名 
     * @param key 
     * @param val 
     */  
    public static void hsetnx(String hName, String key, String value) {  
  
        cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.hSetNX(key.getBytes(),  
                key.getBytes(), value.getBytes()));  
  
    }  
  
    /** 
     * 保存到hash集合中 只在 key 指定的哈希集中不存在指定的字段时,设置字段的值。如果 key 指定的哈希集不存在,会创建一个新的哈希集并与 
     * key 关联。如果字段已存在,该操作无效果。 
     * 
     * @param <T> 
     * 
     * @param hName 
     *            集合名 
     * @param key 
     * @param val 
     */  
    public static <T> void hsetnx(String hName, String key, T t) {  
        hsetnx(hName, key, JSON.toJSONString(t));  
    }  
  
}  

2、重点来了,我们怎么叫我们的jar包加入自启动呢?首先加入autoconfig

package com.ecej.nove.redis.core;  
  
import org.springframework.context.annotation.Configuration;  
import org.springframework.context.annotation.Import;  
  
import com.ecej.nove.redis.config.RedisClusterConfig;  
import com.ecej.nove.redis.config.RedisSentinelConfig;  
import com.ecej.nove.redis.utils.JedisClusterUtils;  
  
@Configuration  
@Import({ RedisClusterConfig.class, RedisSentinelConfig.class, JedisClusterUtils.class })  
public class RedisAutoConfiguration {  
  
}  

在src\main\resources下面增加自启动扫描配置
META-INF/spring.factories

Auto Configure

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.ecej.nove.redis.core.RedisAutoConfiguration

3、至此,配置就全部完成了,下面说下使用
说下Redis使用,如果想在自己的项目中使用redis,如下先加入依赖
<dependency>
<groupId>com.nove</groupId>
<artifactId>xxx-redis</artifactId>
</dependency>

就可以了,然后我们只要配置我们的配置文件,不需要其他多余的工作
redis集群分为两种,sentinel 还有3.x的cluster,根据你自己的需要选择集群配置,配置文件都放在resources下面的
先说sentinel配置
用法:使用com.xxx.nove.redis.utils.JedisClusterUtils这个静态类
remote-redis.properties
这个大家可以直接下载用
xxx.redis.hostName=@xxx.redis.hostName@
xxx.redis.password=@xxx.redis.password@
xxx.redis.mastername=@xxx.redis.mastername@
以下配置可选择增加
xxx.redis.maxIdle=@xxx.redis.maxIdle@
xxx.redis.maxTotal=@xxx.redis.maxTotal@
xxx.redis.maxWaitMillis=@xxx.redis.maxWaitMillis@

这是properties的配置
下面说下POM里面profile的配置
<xxx.redis.hostName>10.32.32.58:26379,10.32.32.58:26380,10.32.32.58:26381</xxx.redis.hostName>
<xxx.redis.mastername>redismaster</xxx.redis.mastername>
<xxx.redis.password><![CDATA[4BZcIv&9]]></xxx.redis.password>
<xxx.redis.maxIdle>10</xxx.redis.maxIdle>
<xxx.redis.maxTotal>1000</xxx.redis.maxTotal>
<xxx.redis.maxWaitMillis>3000</xxx.redis.maxWaitMillis>

下面再说下3.x的配置
remote-redis.properties
xxx.redis.password=@xxx.redis.password@
xxx.redis.hostName=@xxx.redis.hostName@
以下配置可选择增加
xxx.redis.maxIdle=@xxx.redis.maxIdle@
xxx.redis.maxTotal=@xxx.redis.maxTotal@
xxx.redis.maxWaitMillis=@xxx.redis.maxWaitMillis@
xxx.redis.maxRedirects=@xxx.redis.maxRedirects@

下面贴出profile的配置
<xxx.redis.hostName>10.4.89.161:6379</xxx.redis.hostName>
<xxx.redis.maxRedirects>10</xxx.redis.maxRedirects>
<xxx.redis.password></xxx.redis.password>
<xxx.redis.maxIdle>10</xxx.redis.maxIdle>
<xxx.redis.maxTotal>1000</xxx.redis.maxTotal>
<xxx.redis.maxWaitMillis>3000</xxx.redis.maxWaitMillis>
两种配置都有了,那下面说下怎么选择用哪种集群模式
xxx.redis.cluster=true 使用3.x模式
xxx.redis.sentinel=true 使用sentinel模式
注意:这俩配置选一个,放在application.properties中,不要乱放。

OK,全部配置完成,可以开心的使用了


关注公众号,将获得最新文章推送

狍狍的日常生活

相关文章

网友评论

    本文标题:spring boot实际应用(五) redis

    本文链接:https://www.haomeiwen.com/subject/uhuxjxtx.html