Spring Boot 提供了一种非常方便的方式来集成缓存,通过使用 spring-boot-starter-cache 项目,可以快速集成缓存,而且还支持多种缓存技术,包括 Redis 缓存。

下面是集成 Redis 缓存的步骤:

  1. 添加 spring-boot-starter-cache 和 spring-boot-starter-data-redis 依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置 Redis 连接信息:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
  1. 在启动类上加上 @EnableCaching 注解:
@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 在需要使用缓存的方法上加上 @Cacheable、@CachePut、@CacheEvict 等注解:
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    @Cacheable(cacheNames = 'user', key = '#id')
    public User getUserById(Long id) {
        return userRepository.getOne(id);
    }

    @Override
    @CachePut(cacheNames = 'user', key = '#user.id')
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    @Override
    @CacheEvict(cacheNames = 'user', key = '#id')
    public void deleteUserById(Long id) {
        userRepository.deleteById(id);
    }
}

这样就可以很方便地使用 Redis 缓存了。注意,使用 @Cacheable 注解时需要指定 cacheNames 属性,这个属性指定了缓存的名称,可以根据需要指定不同的缓存名称。另外,使用 @CachePut 注解时也需要指定 key 属性,这个属性指定了缓存的 key,通常可以使用方法参数的值来作为 key。

Spring Boot 集成 Redis 缓存:简单易用的教程

原文地址: https://www.cveoy.top/t/topic/owCB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录