簡單基於spring的redis配置(單機和集羣模式)

須要的jar包:spring版本:4.3.6.RELEASE,jedis版本:2.9.0,spring-data-redis:1.8.0.RELEASE;若是使用jackson序列化的話還額外須要:jackson-annotations和jackson-databind包node

spring集成redis單機版:
    1.配置RedisTemplate
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="connectionFactory"/>
            <property name="defaultSerializer" ref="stringRedisSerializer"/>
            <property name="keySerializer" ref="stringRedisSerializer"/>
            <property name="valueSerializer" ref="valueSerializer"/>
        </bean>
    2.配置connectionFactory
        <bean id="connectionFactory"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <!-- 配置ip -->
            <property name="hostName" value="${redis.host}"/>
            <!-- 配置port -->
            <property name="port" value="${redis.port}"/>
            <!-- 是否使用鏈接池-->
            <property name="usePool" value="${redis.usePool}"/>
            <!-- 配置redis鏈接池-->
            <property name="poolConfig" ref="poolConfig"/>
        </bean>
   3.配置鏈接池
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <!--最大空閒實例數-->
            <property name="maxIdle" value="${redis.maxIdle}" />
            <!--最大活躍實例數-->
            <property name="maxTotal" value="${redis.maxTotal}" />
            <!--建立實例時最長等待時間-->
            <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
            <!--建立實例時是否驗證-->
            <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        </bean>

spring集成redis集羣
    1.配置RedisTemplate步驟與單機版一致
    2.配置connectionFactory
        <bean id="connectionFactory"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <!-- 配置redis鏈接池-->    
            <constructor-arg ref="poolConfig"></constructor-arg>
            <!-- 配置redis集羣-->  
         <constructor-arg ref="clusterConfig"></constructor-arg>
            <!-- 是否使用鏈接池-->
            <property name="usePool" value="${redis.usePool}"/>
        </bean>
    3.配置鏈接池步驟與單機版一致
    4.配置redis集羣
        <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
            <property name="maxRedirects" value="3"></property>
            <property name="clusterNodes">
                <set>
                    <bean class="org.springframework.data.redis.connection.RedisClusterNode">
                        <constructor-arg value="${redis.host1}"></constructor-arg>
                        <constructor-arg value="${redis.port1}"></constructor-arg>
                    </bean>
                    <bean class="org.springframework.data.redis.connection.RedisClusterNode">
                        <constructor-arg value="${redis.host2}"></constructor-arg>
                        <constructor-arg value="${redis.port2}"></constructor-arg>
                    </bean>
                    ......
                </set>
            </property>
        </bean>
    或者
        <bean name="propertySource" class="org.springframework.core.io.support.ResourcePropertySource">
            <constructor-arg name="location" value="classpath:properties/spring-redis-cluster.properties" />
        </bean>
        <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
            <constructor-arg name="propertySource" ref="propertySource"/>
        </bean>

序列化配置簡述:redis

1.stringRedisSerializer:因爲redis的key是String類型因此通常使用StringRedisSerializer
2.valueSerializer:對於redis的value序列化,spring-data-redis提供了許多序列化類,這裏建議使用Jackson2JsonRedisSerializer,默認爲JdkSerializationRedisSerializer
3.JdkSerializationRedisSerializer: 使用JDK提供的序列化功能。 優勢是反序列化時不須要提供類型信息(class),但缺點是序列化後的結果很是龐大,是JSON格式的5倍左右,這樣就會消耗redis服務器的大量內存。
4.Jackson2JsonRedisSerializer:使用Jackson庫將對象序列化爲JSON字符串。優勢是速度快,序列化後的字符串短小精悍。但缺點也很是致命,那就是此類的構造函數中有一個類型參數,必須提供要序列化對象的類型信息(.class對象)。

使用spring註解式來配置redis,這裏只配置集羣樣例spring

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    //spring3支持註解方式獲取value 在application裏配置配置文件路徑便可獲取
    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;

    @Value("${spring.redis.cluster.timeout}")
    private Long timeout;

    @Value("${spring.redis.cluster.max-redirects}")
    private int redirects;

    @Value("${redis.maxIdle}")
    private int maxIdle;

    @Value("${redis.maxTotal}")
    private int maxTotal;

    @Value("${redis.maxWaitMillis}")
    private long maxWaitMillis;

    @Value("${redis.testOnBorrow}")
    private boolean testOnBorrow;

    /**
     * 選擇redis做爲默認緩存工具
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        //cacheManager.setDefaultExpiration(60);
        //Map<String,Long> expiresMap=new HashMap<>();
        //expiresMap.put("redisCache",5L);
        //cacheManager.setExpires(expiresMap);
        return cacheManager;
    }

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(){
        Map<String, Object> source = new HashMap<>();
        source.put("spring.redis.cluster.nodes", clusterNodes);
        source.put("spring.redis.cluster.timeout", timeout);
        source.put("spring.redis.cluster.max-redirects", redirects);
        return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
    }

    @Bean
    public JedisConnectionFactory redisConnectionFactory(RedisClusterConfiguration configuration){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxTotal); 
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        poolConfig.setTestOnBorrow(testOnBorrow);
        return new JedisConnectionFactory(configuration,poolConfig);
    }

    /**
     * retemplate相關配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置鏈接工廠
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修飾符範圍,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,好比String,Integer等會跑出異常
        //om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值採用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 設置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
    
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }
}

注意事項:json

1.採用註解式配置redis或者使用@Configuration須要在配置文件中指定掃描什麼哪些包下的配置文件,固然若是是springboot那當我沒說過這句話...緩存

<context:component-scan base-package="com.*"/>

2.spring3支持註解方式獲取Value,可是須要在加載的配置文件配置文件路徑便可,具體值本身指定吧...springboot

<value>classpath:properties/spring-redis-cluster.properties</value>

3.因爲咱們公司原有的框架採用的是spring2.5.6, 而對於spring2 和spring2+主要區別(固然是我本身以爲啊)是把各模塊分紅了不一樣的jar,而對於使用spring-data-redis模板化處理redis的話,單機狀況下spring2.5.6和spring4不會衝突,而若是使用集羣模式須要配置redis集羣的時候就會出現jar包衝突,這個時候就看要如何取決了,能夠直接使用jedisCluster來鏈接redis集羣(不過不少方法都須要本身去寫),也能夠把spring2.5.6替換成高版本的spring4,只是框架替換須要注意的事情更多了啊(咱們公司的直接所有替換沒啥毛病好吧,O(∩_∩)O哈哈~),至於重寫JedisConnectionFactory和RedisClusterConfiguration我還未去嘗試,這個能夠做爲後續補充吧...服務器

4.順便說句,spring4不在支持ibatis了,若是你須要用spring4,又須要鏈接ibatis的話,最粗暴的方式是把spring-orm包換成spring3版本,其餘的jar仍是4版本便可。(固然我這邊直接替換是沒啥問題,但同3同樣可能存在潛在問題啊,因此說嘛,公司有時候仍是須要更新換代下吧...)app

相關文章
相關標籤/搜索