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-starter-cache项目集成redis缓存

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

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