在Spring Boot中使用Redis作为缓存,首先需要添加Spring Boot的Redis依赖和Spring Cache的依赖。以下是Maven的依赖配置:
<!-- Spring Boot Redis Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Spring Boot Cache Abstraction -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>然后在application.properties或application.yml中配置Redis连接信息:
# application.properties
spring.redis.host=localhost
spring.redis.port=6379接下来,在Spring Boot的启动类上添加@EnableCaching注解来启用缓存功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}最后,使用Spring Cache的注解来标记需要缓存的方法和数据:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class SomeService {
@Cacheable(value = "sampleCache", key = "#id")
public SomeObject getObjectById(Long id) {
// 查询数据库或其他资源
return someObject;
}
}在上述代码中,@Cacheable注解标记了getObjectById方法,表示该方法的返回结果将被缓存。value属性指定缓存的名称,key属性指定缓存的键,这里使用方法参数中的id作为缓存的键。
以上就是使用Spring Boot开启Redis缓存的基本步骤。Spring Cache提供了丰富的注解来实现缓存的操作,例如@CachePut(更新缓存)、@CacheEvict(删除缓存)等。