boot使用redis

导读:Redis是一种快速、高效的内存数据库,广泛应用于缓存、消息队列等领域 。在使用Boot框架开发应用时,可以通过Spring Data Redis模块方便地集成Redis , 并实现对Redis的操作 。本文将介绍如何使用Boot集成Redis 。
1. 引入依赖
在pom.xml中引入spring-boot-starter-data-redis依赖:
```
org.springframework.bootspring-boot-starter-data-redis2. 配置Redis连接信息
在application.properties中配置Redis连接信息:
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
3. 使用RedisTemplate进行操作
通过注入RedisTemplate对象 , 即可进行对Redis的操作:
@Autowired
private RedisTemplate redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
4. 使用注解进行缓存
可以使用@Cacheable、@CachePut、@CacheEvict等注解对方法进行缓存操作:
@Cacheable(value = "http://data.evianbaike.com/Redis/user", key = "#id")
public User getUserById(Long id) {
//...
@CachePut(value = "http://data.evianbaike.com/Redis/user", key = "#user.id")
public User updateUser(User user) {
@CacheEvict(value = "http://data.evianbaike.com/Redis/user", key = "#id")
public void deleteUserById(Long id) {
【boot使用redis】总结:通过Spring Data Redis模块,使用Boot框架集成Redis非常方便 。可以通过RedisTemplate对象进行对Redis的操作,也可以使用注解进行缓存操作 。

    推荐阅读