springboot利用yml格式配置远程redis
时间: 2023-09-15 15:21:56 浏览: 178
springboot配置文件yml1
在Spring Boot中,使用yml格式配置远程Redis可以通过以下步骤实现:
1. 在pom.xml文件中添加Redis依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 在application.yml文件中添加Redis的配置信息:
```
spring:
redis:
host: redis.example.com
port: 6379
password: yourpassword
```
其中,host为Redis服务器的IP地址或域名,port为Redis服务器的端口号,默认为6379,password为Redis服务器的密码,如果没有密码可以不填。
3. 在Redis的配置类中进行配置:
```
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisPool redisPoolFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(8);
jedisPoolConfig.setMaxTotal(8);
jedisPoolConfig.setMinIdle(0);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, 10000, password);
return jedisPool;
}
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public RedisCacheManager cacheManager(JedisConnectionFactory jedisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.disableCachingNullValues()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
RedisCacheManager redisCacheManager = RedisCacheManager.builder(jedisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
return redisCacheManager;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName(host);
jedisConnectionFactory.setPort(port);
jedisConnectionFactory.setPassword(password);
return jedisConnectionFactory;
}
}
```
其中,注解@EnableCaching用于启用缓存功能,@Value用于从application.yml中读取Redis的配置信息,redisPoolFactory方法用于创建Jedis连接池,redisTemplate方法用于创建RedisTemplate对象,cacheManager方法用于创建RedisCacheManager对象,jedisConnectionFactory方法用于创建JedisConnectionFactory对象。
4. 在需要使用Redis缓存的地方注入RedisTemplate对象即可:
```
@Autowired
private RedisTemplate<String, Object> redisTemplate;
```
以上就是使用yml格式配置远程Redis的步骤,使用Redis缓存可以提高数据查询的速度,降低数据库的压力。
阅读全文