简单基于spring的redis配置(单机和集群模式)

栏目: Java · 发布时间: 6年前

内容简介:需要的jar包:spring版本:4.3.6.RELEASE,jedis版本:2.9.0,spring-data-redis:1.8.0.RELEASE;如果使用jackson序列化的话还额外需要:jackson-annotations和jackson-databind包序列化配置简述:使用spring注解式来配置redis,这里只配置集群样例

需要的jar包:spring版本:4.3.6.RELEASE,jedis版本:2.9.0,spring-data-redis:1.8.0.RELEASE;如果使用jackson序列化的话还额外需要:jackson-annotations和jackson-databind包

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>

序列化配置简述:

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,这里只配置集群样例

@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;
    }
}

注意事项:

1.采用注解式配置redis或者使用@Configuration需要在配置文件中指定扫描什么哪些包下的配置文件,当然如果是springboot那当我没说过这句话...

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

2.spring3支持注解方式获取Value,但是需要在加载的配置文件配置文件路径即可,具体值自己指定吧...

<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一样可能存在潜在问题啊,所以说嘛,公司有时候还是需要更新换代下吧...)


以上所述就是小编给大家介绍的《简单基于spring的redis配置(单机和集群模式)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Landing Page Optimization

Landing Page Optimization

Tim Ash / Wiley Publishing / 2008-1-29 / USD 29.99

在线阅读本书 How much money are you losing because of poor landing page design? In this comprehensive, step-by-step guide, you’ll learn all the skills necessary to dramatically improve your bottom li......一起来看看 《Landing Page Optimization》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具