基于springboot2.x 整合 Redis的实战
1. 首先,我们需要在pom.xml文件中添加Redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 接下来,在application.properties文件中添加Redis连接信息:
# Redis连接信息
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
3. 创建一个Redis配置类,用于创建RedisTemplate:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
4. 创建一个RedisUtil类,用于封装Redis操作:
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 添加key-value
* @param key
* @param value
*/
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 获取value
* @param key
* @return
*/
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 删除key-value
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
}
5. 在Controller中使用RedisUtil类:
@RestController
@RequestMapping("/blog")
public class BlogController {
@Autowired
private RedisUtil redisUtil;
@GetMapping("/{id}")
public Blog getBlog(@PathVariable Long id) {
Blog blog = (Blog) redisUtil.get("blog_" + id);
if (blog == null) {
blog = blogService.findById(id);
if (blog != null) {
redisUtil.set("blog_" + id, blog);
}
}
return blog;
}
}
6. 这样,我们就成功地实现了基于Spring Boot 2.x的Redis实战博客。现在,每次获取博客时,都会先从Redis中查询,如果Redis中没有,则从数据库中查询,并将结果保存到Redis中。这样可以大大提高博客访问速度,并减少数据库访问次数。