This is the 8th day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Integrate SpringBoot Redission

The following describes three configuration modes of SpringBoot integration Redission

  • Single machine configuration
  • The cluster configuration
  • The sentry configuration

Rely on

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.9.0</version>
</dependency>
Copy the code

The configuration file

See the wrapper class RedisProperties for the basic redis configuration
spring.redis.database=0
spring.redis.password=
spring.redis.timeout=3000
# Redis Thread pool configuration see: Wrapper class RedisPoolProperties
spring.redis.pool.conn-timeout=3000
spring.redis.pool.so-timeout=3000
spring.redis.pool.size=10
Copy the code

The mapping class RedisProperties

@ConfigurationProperties(prefix = "spring.redis", ignoreUnknownFields = false)
@Data
public class RedisProperties {

    private int database;

    /** * The time to wait for the node to reply to the command. The time starts when the command is successfully sent */
    private int timeout;

    private String password;

    private String mode;

    /** * Pool configuration */
    private RedisPoolProperties pool;

    /** * Single-server information */
    private RedisSingleProperties single;

    /** * Cluster information configuration */
    private RedisClusterProperties cluster;

    /** * Sentry configuration */
    private RedisSentinelProperties sentinel;
}
Copy the code

The mapping class RedisPoolProperties

@Data
public class RedisPoolProperties {

    private int maxIdle;

    private int minIdle;

    private int maxActive;

    private int maxWait;

    private int connTimeout;

    private int soTimeout;

    private  int size;

}
Copy the code

Single machine configuration

The configuration file

See: Wrapper class RedisSingleProperties
spring.redis.single.address=127.0.0.1:6379
Copy the code

The mapping class RedisSingleProperties

@Data
public class RedisSingleProperties {
    private  String address;
}
Copy the code

Injecting standalone beans

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class CacheConfiguration {

    @Autowired
    RedisProperties redisProperties;

    /** * Redisson client */
    @Bean
    RedissonClient redissonSingle(a) {
        Config config = new Config();
        String node = redisProperties.getSingle().getAddress();
        node = node.startsWith("redis://")? node :"redis://" + node;
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress(node)
                .setTimeout(redisProperties.getPool().getConnTimeout())
                .setConnectionPoolSize(redisProperties.getPool().getSize())
                .setConnectionMinimumIdleSize(redisProperties.getPool().getMinIdle());
        if (StringUtils.isNotBlank(redisProperties.getPassword())) {
            serverConfig.setPassword(redisProperties.getPassword());
        }
        returnRedisson.create(config); }}Copy the code

The cluster configuration

The configuration file

See: Wrapper class RedisClusterProperties
spring.redis.cluster.scan-interval=1000
spring.redis.cluster.nodes=127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005,127.0.0.1:7006
spring.redis.cluster.read-mode=SLAVE
spring.redis.cluster.retry-attempts=3
spring.redis.cluster.failed-attempts=3
spring.redis.cluster.slave-connection-pool-size=64
spring.redis.cluster.master-connection-pool-size=64
spring.redis.cluster.retry-interval=1500
Copy the code

The mapping class RedisClusterProperties

@Data
public class RedisClusterProperties {

    /** * Cluster status scan interval, in milliseconds */
    private int scanInterval;

    /** * Cluster node */
    private String nodes;

    /** * Default: SLAVE (read only from the service node) Sets the mode for the read operation to select the node. Available values are: SLAVE - Only read from the service node. * MASTER - Read only from the MASTER server node. MASTER_SLAVE - Reads */ on both master and slave nodes
    private String readMode;
    /** * (Secondary node connection pool size) Default value: 64 */
    private int slaveConnectionPoolSize;
    /** * Connection pool size of the primary node) Default value: 64 */
    private int masterConnectionPoolSize;

    /** * (Retry times of command failures) Default value: 3 */
    private int retryAttempts;

    /** * Command retry interval, in milliseconds Default value: 1500 */
    private int retryInterval;

    /** * Maximum number of failed attempts Default value: 3 */
    private int failedAttempts;
}
Copy the code

Injecting cluster beans

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class CacheConfiguration {

    @Autowired
    RedisProperties redisProperties;
    /** * Cluster mode redisson client **@return* /
    @Bean
    RedissonClient redissonCluster(a) {
        System.out.println("cluster redisProperties:" + redisProperties.getCluster());

        Config config = new Config();
        String[] nodes = redisProperties.getCluster().getNodes().split(",");
        List<String> newNodes = new ArrayList(nodes.length);
        Arrays.stream(nodes).forEach((index) -> newNodes.add(
                index.startsWith("redis://")? index :"redis://" + index));

        ClusterServersConfig serverConfig = config.useClusterServers()
                .addNodeAddress(newNodes.toArray(new String[0]))
                .setScanInterval(
                        redisProperties.getCluster().getScanInterval())
                .setIdleConnectionTimeout(
                        redisProperties.getPool().getSoTimeout())
                .setConnectTimeout(
                        redisProperties.getPool().getConnTimeout())
                .setFailedAttempts(
                        redisProperties.getCluster().getFailedAttempts())
                .setRetryAttempts(
                        redisProperties.getCluster().getRetryAttempts())
                .setRetryInterval(
                        redisProperties.getCluster().getRetryInterval())
                .setMasterConnectionPoolSize(redisProperties.getCluster()
                        .getMasterConnectionPoolSize())
                .setSlaveConnectionPoolSize(redisProperties.getCluster()
                        .getSlaveConnectionPoolSize())
                .setTimeout(redisProperties.getTimeout());
        if (StringUtils.isNotBlank(redisProperties.getPassword())) {
            serverConfig.setPassword(redisProperties.getPassword());
        }
        returnRedisson.create(config); }}Copy the code

The guard mode

The configuration file

See: RedisSentinelProperties
spring.redis.sentinel.master=mysentinel-master
spring.redis.sentinel.nodes=127.0.0.1:8888
spring.redis.sentinel.master-onlyWrite=true
spring.redis.sentinel.fail-max=3
Copy the code

The mapping class RedisSentinelProperties

@Data
public class RedisSentinelProperties {

    /** * Sentry master name */
    private String master;

    /**
     * 哨兵节点
     */
    private String nodes;

    /** * Sentry configuration */
    private boolean masterOnlyWrite;

    / * * * * /
    private int failMax;
}
Copy the code

Inject the Sentinel bean

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class CacheConfiguration {

    @Autowired
    RedisProperties redisProperties;

    /** * Sentry mode redisson client *@return* /

    @Bean
    RedissonClient redissonSentinel(a) {
        System.out.println("sentinel redisProperties:" + redisProperties.getSentinel());
        Config config = new Config();
        String[] nodes = redisProperties.getSentinel().getNodes().split(",");
        List<String> newNodes = new ArrayList(nodes.length);
        Arrays.stream(nodes).forEach((index) -> newNodes.add(
                index.startsWith("redis://")? index :"redis://" + index));

        SentinelServersConfig serverConfig = config.useSentinelServers()
                .addSentinelAddress(newNodes.toArray(new String[0]))
                .setMasterName(redisProperties.getSentinel().getMaster())
                .setReadMode(ReadMode.SLAVE)
                .setFailedAttempts(redisProperties.getSentinel().getFailMax())
                .setTimeout(redisProperties.getTimeout())
                .setMasterConnectionPoolSize(redisProperties.getPool().getSize())
                .setSlaveConnectionPoolSize(redisProperties.getPool().getSize());

        if (StringUtils.isNotBlank(redisProperties.getPassword())) {
            serverConfig.setPassword(redisProperties.getPassword());
        }

        returnRedisson.create(config); }}Copy the code

Write in the last

  • 👍🏻 : have harvest, praise encouragement!
  • ❤️ : Collect articles, easy to look back!
  • 💬 : Comment exchange, mutual progress!