Spring Boot配置redis集群

Posted 依米欧

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot配置redis集群相关的知识,希望对你有一定的参考价值。

1、编写redis.properties配置文件

spring.redis.cluster.nodes=172.16.19.128:6300,172.16.1.281:6302,172.16.8.252:6304,172.16.18.121:6301,172.16.1.251:6303,172.168.81.252:6305
spring.redis.password=redis2018

2.配置spring-redis-cluster.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
    default-lazy-init="false">
<!--     <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
        primary="true">
        <property name="connectionFactory" ref="redisConnectionFactory" />
        <property name="exposeConnection" value="true" />
        <property name="keySerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
        <property name="hashKeySerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="hashValueSerializer">
            <bean
                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
    </bean> -->
        <!--配置文件加载 -->
    <bean id="redisClusterResourcePropertySource"
        class="org.springframework.core.io.support.ResourcePropertySource">
        <constructor-arg name="name" value="redis.properties" />
        <constructor-arg name="resource"
            value="classpath:config/redis.properties" />
    </bean>
    <!--redisCluster配置 -->
    <bean id="redisClusterConfiguration"
        class="org.springframework.data.redis.connection.RedisClusterConfiguration">
        <constructor-arg name="propertySource"
            ref="redisClusterResourcePropertySource" />
    </bean>
    <!-- redis服务器中心 -->
    <bean id="redisClusterConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <constructor-arg name="clusterConfig" ref="redisClusterConfiguration" />
        <property name="password" value="${spring.redis.password}" />
    </bean>
    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"
        primary="false">
        <property name="connectionFactory" ref="redisClusterConnectionFactory" />
    </bean>
</beans>

3、编写SpringBeanFactoryUtils类,再在application-context.xml或spring-redis-cluster.xml文件中引入,快速获取一个bean对象

package com.gcard.gwmedia.utils;

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringBeanFactoryUtils   implements ApplicationContextAware {    
    private static ApplicationContext appCtx;    
    /**  
     * 此方法可以把ApplicationContext对象inject到当前类中作为一个静态成员变量。  
     * @param applicationContext ApplicationContext 对象.  
     * @throws BeansException  
     * @author wangdf 
     */    
     
    public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException {    
        appCtx = applicationContext;    
    }  
       
    /** 
     * 获取ApplicationContext 
     * @return 
     * @author wangdf 
     */  
    public static ApplicationContext getApplicationContext(){  
        return appCtx;  
    }  
       
    /**  
     * 这是一个便利的方法,帮助我们快速得到一个BEAN  
     * @param beanName bean的名字  
     * @return 返回一个bean对象  
     * @author wangdf 
     */    
    public static Object getBean( String beanName ) {
        return appCtx.getBean( beanName );
    }    
    @SuppressWarnings("unchecked")
    public static Object getBean( Class requiredType ) {
        return appCtx.getBean(requiredType);
    }    
}

引入一个bean对象

<bean class="com.gcard.gwmedia.utils.SpringBeanFactoryUtils"/>

4、编写RedisUtil类

package com.gcard.getwxcode.utils;

import java.util.HashSet;



import java.util.List;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;


public class RedisUtil {
    private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @SuppressWarnings("rawtypes")
    private static RedisTemplate getRedisTemplate() {
        return (RedisTemplate) SpringBeanFactoryUtils.getBean("redisTemplate");
    }
    @SuppressWarnings("rawtypes")
    private static StringRedisTemplate getStringRedisTemplate() {
        return (StringRedisTemplate) SpringBeanFactoryUtils.getBean("stringRedisTemplate");
    }
    @SuppressWarnings("unchecked")
    public static Long addRedisSet(String redisKey, Object value) {
        Long result = getRedisTemplate().opsForSet().add(redisKey, value);
        if (logger.isDebugEnabled()) {
            logger.debug("result=" + result);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static Long getRedisZsetSize(String redisKey) {
        Long result = getRedisTemplate().opsForZSet().size(redisKey);
        if (logger.isDebugEnabled()) {
            logger.debug("result=" + result);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static Set<String> getRedisSet(String redisKey) {
        if (StringUtils.isNotBlank(redisKey)) {
            Set<String> set = getRedisTemplate().opsForSet().members(redisKey);
            return set;
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static void deleteRedisSet(String redisKey, String entityId) {
        getRedisTemplate().opsForSet().remove(redisKey, entityId);
    }

    @SuppressWarnings("unchecked")
    public static Long addRedisListLeftPush(String redisKey, Object value) {
        Long result = getRedisTemplate().opsForList().leftPush(redisKey, value);
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + result);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static Long addRedisListRightPush(String redisKey, Object value) {
        Long result = getRedisTemplate().opsForList().rightPush(redisKey, value);
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + result);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static void deleteRedisList(String redisKey, String entityId) {
        if (logger.isDebugEnabled()) {
            logger.debug(redisKey);
        }
        getRedisTemplate().opsForList().remove(redisKey, 0, entityId);
    }

    @SuppressWarnings("unchecked")
    public static List getRedisList(String redisKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("getRedisList(..) the redisKey is " + redisKey);
        }
        List result = getRedisTemplate().opsForList().range(redisKey, 0, -1);
        return result;
    }

    @SuppressWarnings("unchecked")
    public static List getRedisListByParam(PageParameter pageParm, String redisKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("getRedisList(..) the redisKey is " + redisKey);
        }
        int startRow = calculateStartRow(pageParm);
        int endRow = calculateEndRow(pageParm, startRow);
        List result = getRedisTemplate().opsForList().range(redisKey, startRow, endRow);
        return result;
    }

    @SuppressWarnings("unchecked")
    public static void addRedisString(String redisKey, String value) {
        if (logger.isDebugEnabled()) {
            logger.debug("addRedisString(..) the redisKey is " + redisKey);
        }
        getRedisTemplate().boundValueOps(redisKey).set(value);
    }

    @SuppressWarnings("unchecked")
    public static void addRedisStringIncrement(String redisKey, long value) {
        if (logger.isDebugEnabled()) {
            logger.debug("addRedisString(..) the redisKey is " + redisKey);
        }
        getRedisTemplate().boundValueOps(redisKey).increment(value);
    }

    @SuppressWarnings("unchecked")
    public static String getRedisString(String redisKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("getRedisString(..) the redisKey is " + redisKey);
        }
        Object object = getRedisTemplate().boundValueOps(redisKey).get();
        String result = String.valueOf(object);
        return result;
    }
    @SuppressWarnings("unchecked")
    public static String getRedisStringValue(String redisKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("getRedisString(..) the redisKey is " + redisKey);
        }
        Object object = getStringRedisTemplate().boundValueOps(redisKey).get();
        String result = String.valueOf(object);
        return result;
    }
    @SuppressWarnings("unchecked")
    public static String getRedisStringByParam(PageParameter pageParam, String redisKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("getRedisStringByParam(..) the redisKey is " + redisKey);
        }
        int startRow = calculateStartRow(pageParam);
        int endrow = calculateEndRow(pageParam, startRow);
        Object object = getRedisTemplate().boundValueOps(redisKey).get(startRow, endrow);
        String result = String.valueOf(object);
        return result;
    }

    @SuppressWarnings("unchecked")
    public static void deleteRedisString(String redisKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("deleteRedisString(..) the redisKey is " + redisKey);
        }
        getRedisTemplate().delete(redisKey);
    }

    @SuppressWarnings("unchecked")
    public static void addRedisMap(String redisKey, String hashKey, Object value) {
        if (logger.isDebugEnabled()) {
            logger.debug("addRedisMap(..) the redisKey is " + redisKey);
        }
        getRedisTemplate().opsForHash().put(redisKey, hashKey, value);
    }

    @SuppressWarnings("unchecked")
    public static void deleteRedisMap(String redisKey, String[] hashKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("deleteRedisMap(..) the redisKey is " + redisKey);
        }
        getRedisTemplate().opsForHash().delete(redisKey, hashKey);
    }

    @SuppressWarnings("unchecked")
    public static Map<Object, Object> getRedisMap(String redisKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("getRedisMap(..) the redisKey is " + redisKey);
        }
        Map<Object, Object> result = getRedisTemplate().opsForHash().entries(redisKey);
        return result;
    }

    @SuppressWarnings("unchecked")
    public static Map getRedisMapByHashKey(String redisKey, String hashKey) {
        if (logger.isDebugEnabled()) {
            logger.debug("getRedisMap(..) the redisKey is " + redisKey);
        }
        Map result = (Map) getRedisTemplate().opsForHash().get(redisKey, hashKey);
        return result;
    }

    @SuppressWarnings("unchecked")
    public static boolean addRedisZset(String redisKey, String entityId, Double score) {
        Boolean result = getRedisTemplate().opsForZSet().add(redisKey, entityId, score);
        if (logger.isDebugEnabled()) {
            logger.debug("addRedisZset(..) the result is " + result);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static void addRedisZsetIncrementScore(String redisKey, Object value, Double score) {
        getRedisTemplate().opsForZSet().incrementScore(redisKey, value, score);
        if (logger.isDebugEnabled()) {
            logger.debug("addRedisZsetIncrementScore(..) the score is " + score);
        }
    }

    @SuppressWarnings("unchecked")
    public static Double addRedisZsetIncrementScore(String redisKey, String value, Double score) {
        Double _score = getRedisTemplate().opsForZSet().incrementScore(redisKey, value, score);
        if (logger.isDebugEnabled()) {
            logger.debug("addRedisZsetIncrementScore(..) the return _score is " + _score);
        }
        return _score;
    }

    @SuppressWarnings("unchecked")
    public static void addRedisZset(String redisKey, Object entityId, Double score) {
        getRedisTemplate().opsForZSet().add(redisKey, entityId, score);
    }

    @SuppressWarnings("unchecked")
    public static void deleteRedisZset(String redisKey, String entityId) {
        if (logger.isDebugEnabled()) {
            logger.debug("deleteRedisZset(..) the redisKey is " + redisKey);
        }
        getRedisTemplate().opsForZSet().remove(redisKey, entityId);
        getRedisTemplate().opsForZSet().removeRange(redisKey, 0, -1);
    }

    @SuppressWarnings("unchecked")
    public static void removeZsetRange(String redisKey, long start, long end) {
        if (logger.isDebugEnabled()) {
            logger.debug("removeZsetRange(..) the redisKey is " + redisKey);
        }
        getRedisTemplate().opsForZSet().removeRange(redisKey, start, end);
    }

    @SuppressWarnings("unchecked")
    public static void deleteRedisZsetByValue(String redisKey, Object value) {
        getRedisTemplate().opsForZSet().remove(redisKey, value);
    }

    @SuppressWarnings("unchecked")
    public static void deleteRedisZsetByScore(String redisKey, double score) {
        if (logger.isDebugEnabled()) {
            String message = String.format("score=%s", score);
            logger.debug(message);
        }
        getRedisTemplate().opsForZSet().removeRangeByScore(redisKey, score, score);
    }

    @SuppressWarnings("unchecked")
    public static Set<String> getRedisZset(String redisKey) {
        if (StringUtils.isNotBlank(redisKey)) {
            Set<String> set = getRedisTemplate().opsForZSet().range(redisKey, 0, -1);
            return set;
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static Object getRedisZsetByScore(String redisKey, long score) {
        if (StringUtils.isNotBlank(redisKey)) {
            Set<String> set = getRedisTemplate().opsForZSet().rangeByScore(redisKey, score, score);
            if (set.isEmpty()) {
                return null;
            } else {
                Object obj = set.iterator().next();
                return obj;
            }
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static Double getRedisZsetByValue(String redisKey, int value) {
        if (StringUtils.isNotBlank(redisKey)) {
            double score = getRedisTemplate().opsForZSet().score(redisKey, value);
            return score;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static Double getRedisZsetByStringValue(String redisKey, String value) {
        if (StringUtils.isNotBlank(redisKey)) {
            Double score = getRedisTemplate().opsForZSet().score(redisKey, value);
            return score;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static Set<Object> getRedisZsetReverse(String redisKey,PageParameter parameter){
        if(StringUtils.isNotBlank(redisKey)){
            Set<Object> set = new HashSet<>();
            if(parameter == null){
                set = getRedisTemplate().opsForZSet().reverseRange(redisKey, 0, 1);
            }else{
                int startRow = calculateStartRow(parameter);
                int endRow =  calculateEndRow(parameter,startRow);
                set = getRedisTemplate().opsForZSet().reverseRange(redisKey, startRow, endRow);
            }
            return set;
        }else{
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static Long getRedisZsetRank(String redisKey, String value) {
        if (StringUtils.isNotBlank(redisKey)) {
            Long rank = getRedisTemplate().opsForZSet().reverseRank(redisKey, value);
            if(rank == null){
                return null;
            }else{
                rank = rank + 1;
                return rank;
            }
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static boolean hasRedisKey(String redisKey) {
        boolean isflag = false;
        if (StringUtils.isNotBlank(redisKey)) {
            isflag = getRedisTemplate().hasKey(redisKey);
        }
        return isflag;
    }

    @SuppressWarnings("unchecked")
    public static void expireMinutes(String redisKey, int timeout) {
        getRedisTemplate().expire(redisKey, timeout, TimeUnit.MINUTES);
    }

    @SuppressWarnings("unchecked")
    public static void expireSeconds(String redisKey, int timeout) {
        getRedisTemplate().expire(redisKey, timeout, TimeUnit.SECONDS);
    }

    public static int calculateStartRow(PageParameter pageParm) {
        int startRow = pageParm.getPage() > 0 ? (pageParm.getPage() - 1) * pageParm.getRows() : 0;
        return startRow;
    }

    public static int calculateEndRow(PageParameter pageParm, int startRow) {
        int endRow = startRow + pageParm.getRows() * (pageParm.getPage() > 0 ? 1 : 0);
        if (endRow > 0) {
            endRow = endRow - 1;
        }
        return endRow;
    }
}

 

以上是关于Spring Boot配置redis集群的主要内容,如果未能解决你的问题,请参考以下文章

在Spring Boot 上配置Redis Cluster出现的异常

如何使用spring boot 2.x为redis集群设置密码

spring boot 整合 redis

Redis 集群与 Spring Boot 的集成

spring boot:使用redis cluster集群作为分布式session(redis 6.0.5/spring boot 2.3.1)

spring boot redis(连接,增删改查,集群,和session一起使用)