Redis集群条件下JedisCluster和SpringBoot整合的使用

引入redis jar


        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

application.properites 中的配置



#redis配置
#集群节点
redis.cache.clusterNodes=192.168.87.55:6379,192.168.87.56:6379
#请求过期时间
redis.cache.commandTimeout=5000
#缓存时间
redis.cache.expireSeconds=120


#redis 连接池相关配置
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.timeout=5000

设置值


@Component
@ConfigurationProperties(prefix = "redis.cache")
public class RedisProperties {


    private int    expireSeconds;
    private String clusterNodes;
    private int    commandTimeout;

    public int getExpireSeconds() {
        return expireSeconds;
    }

    public void setExpireSeconds(int expireSeconds) {
        this.expireSeconds = expireSeconds;
    }

    public String getClusterNodes() {
        return clusterNodes;
    }

    public void setClusterNodes(String clusterNodes) {
        this.clusterNodes = clusterNodes;
    }

    public int getCommandTimeout() {
        return commandTimeout;
    }

    public void setCommandTimeout(int commandTimeout) {
        this.commandTimeout = commandTimeout;
    }
}

注入redisCluster bean


@Configuration
public class JedisClusterConfig {

    @Autowired
    private RedisProperties redisProperties;

    /**
     * 注意:
     * 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
     * @return
     */
    @Bean
    public JedisCluster getJedisCluster() {

        String[] serverArray = redisProperties.getClusterNodes().split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
        Set<HostAndPort> nodes = new HashSet<>();

        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }

        return new JedisCluster(nodes, redisProperties.getCommandTimeout());
    }


}

redisCluster utils方法


@Component
public class RedisMapper {

    private static String oldTime = null;

    @Autowired
    JedisCluster jedisCluster;



    /**更据key值查找*/
    public CollaboratorKeyAndValue getByKey(String key){
        CollaboratorKeyAndValue keyAndValue=null;

        String str=jedisCluster.get("getValue_"+key);
        if (str != null){
            keyAndValue= JSONObject.parseObject(str,CollaboratorKeyAndValue.class);
        }

        return keyAndValue;

    }




    /**根据接口id查找*/
    public VerificationFrequencyControl getByinterfaceId(String interfaceId){
        VerificationFrequencyControl con=null;
        /**得到json对象 存的时候也要是json对象的方式*/
        String str=jedisCluster.get("getValue_"+interfaceId);
        if (str != null){

            con=JSONObject.parseObject(str,VerificationFrequencyControl.class);
        }

        return con;
    }


    /**保存方法*/
    public void insert(Object object){

       String json= JSON.toJSONString(object);
       if (json != null){

            if (object.getClass() == CollaboratorKeyAndValue.class) {
                /**是CollaboratorKeyAndValue对象*/
                CollaboratorKeyAndValue co=(CollaboratorKeyAndValue)object;
                 /**CollaboratorKeyAndValue对象存储的是Value+key的方式*/
              jedisCluster.set("getValue_"+co.getKey(),json);
            }else if (object.getClass() == VerificationFrequencyControl.class){
                 /**是VerificationFrequencyControl对象*/
                VerificationFrequencyControl co=(VerificationFrequencyControl)object;
                /**VerificationFrequencyControl+接口id的方式*/
                jedisCluster.set("getValue_"+co.getInterfaceId(),json);
            }

       }

    }


    /**判断key是否存在*/
    public boolean hasKey(String key)
    {
        return jedisCluster.exists(key);
    }

    /**根据key获取Value*/
    public String get(String key) {

        return jedisCluster.get(key);
    }


    /**
     * 设置缓存,并且自己指定过期时间
     * @param key
     * @param value
     * @param expireTime 过期时间
     */
    public void setWithExpireTime( String key, String value, int expireTime) {
        jedisCluster.set(key,value);
        jedisCluster.pexpire(key,expireTime);
    }



    /**
     * 删除指定key的缓存
     * @param key
     */
    public void delete(String key) {
        long o =jedisCluster.del(key);
        System.out.println(o+"...");
    }


    /**
     * 删除所有key的缓存
     *
     */
    public void deleteALl(String key) {

        Set<String> set = jedisCluster.hkeys(key);
        System.out.println("删除的key length " + set.size());
        for (String s : set) {
            System.out.println("删除的key" + key);
            jedisCluster.del(s);
        }
    }




        /**
         * 频率控制方法1  100ms调用一次
         *
         */
    public Boolean freControlOne() {

        /**reids取值*/
         String value=get("getTime_"+100+"ms");
         System.out.println("频率控制方法1  100ms调用一次 redis取值:"+value);
         if (value == null){
             /**表明Value已经过期 也就是时间间隔超过100ms 可以在调用 再次设置值*/
              setWithExpireTime("getTime_"+100+"ms","100ms",100);
              return true;
         }

        /**Value没有过期 还不能进行调用*/
         return false;

        }



    /**
     * 频率控制方法2  一天调用10次
     *
     */
    public Boolean freControlTwo() {

       String  newTime=new SimpleDateFormat("yyyy-MM-dd").format(new Date());


        //没有计数前得到的是Value 存进去的Value值
        String value=get("getTime_"+newTime);
        /**已经过了一天*/
        if (!newTime.equalsIgnoreCase(oldTime)){
            jedisCluster.del("getTime_"+oldTime);
        }

        if (value == null){
            /**第一调用 还未超过10次*/
            /**每次访问接口增加 1 */
            oldTime=newTime;
            /**value初始值是 1 以后的每次访问 value都会加 1  */
            jedisCluster.set("getTime_"+newTime,"1");

            return true;
        }

        String redisValue=jedisCluster.get("getTime_"+newTime);
        if (Long.parseLong(redisValue) >=  10){
            /**超出一天的 接口调用限度*/
            return false;
        }

        /**增加1 */
        jedisCluster.incrBy("getTime_"+newTime,1);

        return true;

    }



}

猜你喜欢

转载自blog.csdn.net/didi7696/article/details/80695367