Spring-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 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>
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,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; } }
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.*"/>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.
