Home  >  Article  >  Java  >  Java Redis Redisson configuration example analysis

Java Redis Redisson configuration example analysis

WBOY
WBOYforward
2023-04-25 08:19:061323browse

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

  1. Asynchronous data loss

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

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete