Required Maven
<!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <!-- 多台相同应用(负载均),Session共享 --> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.17.5</version> </dependency>
application-redis.yml
spring: redis: host: 106.12.174.220 port: 6379 password: 123456 #没有密码就保留空 timeout: 5000 jedis: pool: max-active: 1000 # 池在给定时间可以分配的最大连接数。使用负值表示无限制。 max-idle: 50 #池中“空闲”连接的最大数量。使用负值表示空闲连接的数量不受限制 min-idle: 10 # 目标是池中要维护的最小空闲连接数。此设置只有在它和逐出运行之间的时间均为正值时才有效。 max-wait: -1 # 在池耗尽时引发异常之前,连接分配应阻止的最长时间。使用负值无限期阻塞。 redisson: tokenName: Authorization # 用于分布式锁的唯一标识,一般使用token如果没有找到,就找sessionId session: store-type: redis #设置session保存为默认redis的方式 ,可以解决分布式session不一致问题
Session shared configuration
SessionConfig
import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @Configuration //设置session的默认在redis中的存活时间 @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 7200) //Session过期时间,2小时,默认1800秒(半小时) -1 永不过期 public class SessionConfig {}
SessionInitializer
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; //初始化Session配置 public class SessionInitializer extends AbstractHttpSessionApplicationInitializer { public SessionInitializer() { super(SessionConfig.class); } }
Redisson configuration
import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.redisson.config.SingleServerConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RedissonConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private String port; @Value("${spring.redis.password}") private String password; @Bean public RedissonClient getRedisson() { Config config = new Config(); SingleServerConfig singleServerConfig = config.useSingleServer(); singleServerConfig.setAddress("redis://" + host + ":" + port).setPassword(password); return Redisson.create(config); } }
Other Redisson Config configuration methods
Redisson Config (stand-alone version configuration)
Config config = new Config(); config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password);
Redisson Config (Sentinel version configuration)
It can be understood that if the master node is lost, the child nodes will automatically supplement the master node
Config config = new Config(); config.useSentinelServers().addSentinelAddress( "redis://172.29.3.245:26378","redis://172.29.3.245:26379", "redis://172.29.3.245:26380") .setMasterName("mymaster") .setPassword("a123456");
Redisson's Config (Master-slave version configuration)
Yes It is understood as the read-write separation of redis, but if the master node hangs up, the child nodes cannot be automatically upgraded to the master node like the sentinel mode.
Config config = new Config(); config.useMasterSlaveServers() //可以用"rediss://"来启用SSL连接 .setMasterAddress("redis://192.168.81.145:6379")//主节点 //从节点 .addSlaveAddress("redis://192.168.81.146:6379") .addSlaveAddress("redis://192.168.81.148:6379") .setPassword("123456");
Redisson's Config (cluster mode)
Config config = new Config(); config.useClusterServers() .setScanInterval(2000) // 集群状态扫描间隔时间,单位是毫秒 .addNodeAddress("redis://127.0.0.1:7000") .addNodeAddress("redis://127.0.0.1:7001") .addNodeAddress("redis://127.0.0.1:7002") .setPassword("123456");
Redisson's Config (red lock mode)
The node premise of red lock mode must be the master node, or all stand-alone Redis
Solution: Sentinel/master-slave/cluster, these modes, Problems that arise
Asynchronous data loss
Split-brain problem.
Sometimes the program is so clever. For example, when a node hangs up, multiple clients acquire the lock at the same time. If you can accept this small probability of error, then there will be no problem using the previous replication solution. Otherwise, we recommend that you implement the solution described below.
Assume there are 5 redis nodes. There is neither master-slave nor cluster relationship between these nodes. The client uses the same key and random value to request lock on 5 nodes. The timeout period for requesting the lock should be less than the automatic lock release time. When the lock is requested on 3 (more than half) redis, the lock is truly acquired. If the lock is not obtained, some of the locked redis will be released.
Config config1 = new Config(); config1.useSingleServer().setAddress("redis://172.29.1.180:5378") .setPassword("123456"); RedissonClient redissonClient1 = Redisson.create(config1); Config config2 = new Config(); config2.useSingleServer().setAddress("redis://172.29.1.180:5379") .setPassword("123456"); RedissonClient redissonClient2 = Redisson.create(config2); Config config3 = new Config(); config3.useSingleServer().setAddress("redis://172.29.1.180:5380") .setPassword("123456"); RedissonClient redissonClient3 = Redisson.create(config3); String resourceName = "REDLOCK"; RLock lock1 = redissonClient1.getLock(resourceName); RLock lock2 = redissonClient2.getLock(resourceName); RLock lock3 = redissonClient3.getLock(resourceName); // 同时给3个redis上锁 RedissonRedLock redLock = new RedissonRedLock(lock1, lock2, lock3); boolean isLock; try { isLock = redLock.tryLock(500, 30000, TimeUnit.MILLISECONDS); System.out.println("isLock = "+isLock); if (isLock) { //TODO if get lock success, do something; Thread.sleep(30000); } } catch (Exception e) { } finally { // 无论如何, 最后都要解锁 System.out.println(""); redLock.unlock(); }
The above is the detailed content of Java Redis Redisson configuration example analysis. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.