Home > Java > javaTutorial > Spring-based redis configuration (stand-alone and cluster mode)

Spring-based redis configuration (stand-alone and cluster mode)

不言
Release: 2019-02-21 14:47:52
forward
2261 people have browsed it

This article brings you content about spring-based redis configuration (stand-alone and cluster mode). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Required jar package: spring version: 4.3.6.RELEASE, jedis version: 2.9.0, spring-data-redis:1.8.0.RELEASE; if you use jackson serialization, you also need: jackson -annotations and jackson-databind package

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>
Copy after login

Brief description of serialization configuration:

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对象)。
Copy after login

Use spring annotations to configure redis, only cluster examples are configured here

@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;
    }
}
Copy after login

Notes :

1. To configure redis using annotations or use @Configuration, you need to specify in the configuration file what configuration files are scanned under which packages. Of course, if it is springboot, then I have not said this...

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

2.spring3 supports annotation method to obtain Value, but you need to configure the file path in the loaded configuration file. You can specify the specific value yourself...

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

3. Due to our company’s original The framework uses spring2.5.6. The main difference between spring2 and spring2 (of course, in my opinion) is that each module is divided into different jars. When using spring-data-redis to template redis, the stand-alone situation There will be no conflict between spring 2.5.6 and spring 4, but if you use cluster mode and need to configure the redis cluster, jar package conflicts will occur. At this time, it depends on how to decide. You can directly use jedisCluster to connect to the redis cluster (but many methods You need to write it yourself), you can also replace spring2.5.6 with a higher version of spring4, but there are more things to pay attention to when replacing the framework (our company's direct replacement of all is fine, okay, O(∩_∩)O Haha~), as for rewriting JedisConnectionFactory and RedisClusterConfiguration, I haven’t tried it yet. This can be used as a follow-up supplement...

4. By the way, spring4 no longer supports ibatis. If you need to use spring4, then If you need to connect to ibatis, the crudest way is to change the spring-orm package to spring 3 version, and other jars can still be version 4. (Of course, there is no problem with direct replacement here, but there may be potential problems like 3, so the company still needs to update sometimes...)

The above is the detailed content of Spring-based redis configuration (stand-alone and cluster mode). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template