SpringBoot实现自定义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);
}
各个参数含义
setAddress
:连接的地址和端口setPassword
:密码setConnectionPoolSize
:设置连接池的大小setConnectionMinimumIdleSize
:设置连接池的最小空闲连接数setIdleConnectionTimeout
:设置连接的最大空闲时间(单位:毫秒),超过该时间的空闲连接将被关闭setConnectTimeout
:设置连接超时时间(单位:毫秒)setRetryAttempts
:设置连接重试次数setRetryInterval
:设置连接重试的间隔时间(单位:毫秒)setPingConnectionInterval
:设置定期检查连接是否可用的时间间隔(单位:毫秒)setKeepAlive
:设置是否保持长连接