search
HomeJavajavaTutorialSpring-based redis configuration (stand-alone and cluster mode)

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>
            <property></property>
            <property></property>
            <property></property>
            <property></property>
        </bean>
    2.配置connectionFactory
        <bean>
            <!-- 配置ip -->
            <property></property>
            <!-- 配置port -->
            <property></property>
            <!-- 是否使用连接池-->
            <property></property>
            <!-- 配置redis连接池-->
            <property></property>
        </bean>
   3.配置连接池
        <bean>
            <!--最大空闲实例数-->
            <property></property>
            <!--最大活跃实例数-->
            <property></property>
            <!--创建实例时最长等待时间-->
            <property></property>
            <!--创建实例时是否验证-->
            <property></property>
        </bean>

spring集成redis集群
    1.配置RedisTemplate步骤与单机版一致
    2.配置connectionFactory
        <bean>
            <!-- 配置redis连接池-->    
            <constructor-arg></constructor-arg>
            <!-- 配置redis集群-->  
         <constructor-arg></constructor-arg>
            <!-- 是否使用连接池-->
            <property></property>
        </bean>
    3.配置连接池步骤与单机版一致
    4.配置redis集群
        <bean>
            <property></property>
            <property>
                <set>
                    <bean>
                        <constructor-arg></constructor-arg>
                        <constructor-arg></constructor-arg>
                    </bean>
                    <bean>
                        <constructor-arg></constructor-arg>
                        <constructor-arg></constructor-arg>
                    </bean>
                    ......
                </set>
            </property>
        </bean>
    或者
        <bean>
            <constructor-arg></constructor-arg>
        </bean>
        <bean>
            <constructor-arg></constructor-arg>
        </bean>

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

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> expiresMap=new HashMap();
        //expiresMap.put("redisCache",5L);
        //cacheManager.setExpires(expiresMap);
        return cacheManager;
    }

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(){
        Map<string> 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> redisTemplate(JedisConnectionFactory factory) {

        RedisTemplate<string> 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;
    }
}</string></string></string></string>

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...

<component-scan></component-scan>

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>

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function