java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot自定义Redis连接

SpringBoot实现自定义Redis的连接的流程步骤

作者:yang-2307

Spring Boot 自定义 Redis 主要是指在基于 Spring Boot 的应用程序中,当你需要更深入地控制或扩展对 Redis 数据库的操作,而不是仅仅依赖 Spring Data Redis 的默认配置,本文给大家介绍了SpringBoot实现自定义Redis的连接的流程步骤,需要的朋友可以参考下

1.docker安装Redis

docker run -p 6379:6379 --name redis -v /mydata/redis/data:/data -v /mydata/redis/conf/redis.conf:/etc/redis/redis.conf -d redis redis-server /etc/redis/redis.conf

2.maven 的pom文件导包

<dependency>
     	<groupId>org.redisson</groupId>
     	<artifactId>redisson-spring-boot-starter</artifactId>
</dependency>
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
 </dependency>

3.自定义属性

在application.yml文件中加入你自己想要的配置

redis:
	config:
		host: 192.168.200.142 #填你redis安装的电脑的ip
	  	port: 6379
	  	password: 你的密码
	  	pool-size: 10
	  	min-idle-size: 5
	  	idle-timeout: 30000
	  	connect-timeout: 5000
	  	retry-attempts: 3
	  	retry-interval: 1000
	  	ping-interval: 60000
	  	keep-alive: true

4.读取配置

@Data
@ConfigurationProperties(prefix = "redis.config", ignoreInvalidFields = true)
public class RedisClientConfigProperties {

    private String host;
    
    private int port;

    private String password;

    private int poolSize = 64;

    private int minIdleSize = 10;

    private int idleTimeout = 10000;

    private int connectTimeout = 10000;

    private int retryAttempts = 3;

    private int retryInterval = 1000;

    private int pingInterval = 0;

    private boolean keepAlive = true;

}

ignoreInvalidFields字段含义

当这个属性设置为true时,Spring会忽略配置文件中那些与配置类字段不匹配的属性。这意味着,如果配置文件中存在与配置类字段不存在的属性,Spring不会抛出异常,而是忽略这些属性。

注入容器

@Configuration
@EnableConfigurationProperties(RedisClientConfigProperties.class)
public class RedisClientConfig {

    @Bean("redissonClient")
    public RedissonClient redissonClient(ConfigurableApplicationContext applicationContext, RedisClientConfigProperties properties) {
        Config config = new Config();
        
        //设置编码器
        config.setCodec(new JsonJacksonCodec());

        config.useSingleServer()
                .setAddress("redis://" + properties.getHost() + ":" + properties.getPort())
                .setPassword(properties.getPassword())
                .setConnectionPoolSize(properties.getPoolSize())
                .setConnectionMinimumIdleSize(properties.getMinIdleSize())
                .setIdleConnectionTimeout(properties.getIdleTimeout())
                .setConnectTimeout(properties.getConnectTimeout())
                .setRetryAttempts(properties.getRetryAttempts())
                .setRetryInterval(properties.getRetryInterval())
                .setPingConnectionInterval(properties.getPingInterval())
                .setKeepAlive(properties.isKeepAlive())
        ;

        return Redisson.create(config);
    }

各个参数含义

到此这篇关于SpringBoot实现自定义Redis的连接的流程步骤的文章就介绍到这了,更多相关SpringBoot自定义Redis连接内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文