为 Spring Boot 应用添加 Redis Caching

非必须,但如果配置了需补充相应的依赖,否则会出错

#type: redis

redis:

过期时间5秒,默认单位:毫秒,等同于设置成 5s、5S

time-to-live: 5000

key-prefix: cn.mariojd.cache.

cache-null-values: false

  1. 添加实体,实现 Serializable 接口

@Data

@Entity

@Builder

@NoArgsConstructor

@AllArgsConstructor

public class User implements Serializable {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Integer id;

private String name;

}

定义 Repository 接口:

public interface UserRepository extends JpaRepository<User, Integer> {

}

  1. 编写 Service,进行缓存规则配置,核心注解有:@CacheConfig、@Cacheable(缓存新增)、@CachePut(缓存更新)、@CacheEvict(缓存删除)

@Slf4j

@Service

@CacheConfig(cacheNames = “user”)

public class UserService {

@Resource

private UserRepository userRepository;

/**

* Key name: key-prefix.classSimpleName.methodName?pn=xxx&ps=xxx&sort=xxx

*/

@Cacheable(key = “#root.targetClass.simpleName+‘.’+#root.methodName+‘?pn=’+#pageable.pageNumber+‘&ps=’+#pageable.pageSize+‘&sort=’+#pageable.sort.toString()”)

public Page page(Pageable pageable) {

return userRepository.findAll(pageable);

}

@Cacheable(key = “‘user.’+#userId”, unless = “#result == null”)

public Optional get(int userId) {

return userRepository.findById(userId);

}

@Transactional

public User add(String name) {

User user = User.builder().name(name).build();

return userRepository.save(user);

}

@CachePut(key = “‘user.’+#userId”, unless = “#result == null”)

@Transactional

public Optional update(int userId, String name) {

Optional userOptional = userRepository.findById(userId);

userOptional.ifPresent(user -> {

user.setName(name);

userRepository.save(user);

});

return userOptional;

}

@CacheEvict(key = “‘user.’+#userId”)

@Transactional

public void delete(int userId) {

userRepository.findById(userId).ifPresent(user -> userRepository.delete(user));

}

}

  1. 缓存测试,为启动类添加:@EnableCaching

@Slf4j

@EnableCaching

@SpringBootApplication

public class SpringBootCacheApplication implements ApplicationRunner {

public static void main(String[] args) {

new SpringApplicationBuilder()

.sources(SpringBootCacheApplication.class)

.bannerMode(Banner.Mode.OFF)

.web(WebApplicationType.NONE)

.run(args);

log.info(“\n”);

}

@Resource

private UserRepository userRepository;

@PostConstruct

public void init() {

// 初始化数据

for (int i = 0; i < 10; i++) {

User user = User.builder().name(“ZS” + i).build();

userRepository.save(user);

}

}

@Resource

private UserService userService;

@Resource

private Environment environment;

@Override

public void run(ApplicationArguments args) throws InterruptedException {

// 测试缓存,观察是否有SQL输出

PageRequest pageable = PageRequest.of(0, 5);

userService.page(pageable);

for (int i = 0; i < 5; i++) {

userService.page(pageable);

log.info(“Reading page cache…”);

}

// 由于配置是5秒中后缓存失效,这里休眠后重新读取

TimeUnit.MILLISECONDS.sleep(Integer.parseInt(environment.getProperty(“spring.cache.redis.time-to-live”, “5000”)));

log.warn("Page Cache expired : " + userService.page(pageable).getT
otalElements());

log.info(“\n”);

// Test CRUD Cache![enter description here]( )

User user = userService.add(“李四”);

int userId = user.getId();

userService.get(userId);

log.info(“Reading user cache…” + userService.get(userId));

userService.update(userId, “王五”);

log.info(“Reading new user cache…” + userService.get(userId));

userService.delete(userId);

log.warn("User Cache delete : " + userService.get(userId));

}

}

从图中的红框部分输出可以看到,这些查询走了缓存,如果需要在 redis 中查看缓存内容,可以将配置中的 TTL 时间调大:

为 Spring Boot 应用添加 Redis Caching

测试输出

扩展操作

Spring 允许开发者们通过自定义 KeyGenerator 来覆盖繁琐的 Key 定义(非必须),同时也允许我们配置自定义的 CacheManager,下面来看看如何编写 KeyGenerator:

为 Spring Boot 应用添加 Redis Caching

@CacheConfig

@Slf4j

public class CustomKeyGenerator implements KeyGenerator {

@Override

public Object generate(Object target, Method method, Object… params) {

// 类名.方法名.参数值

String keySuffix = target.getClass().getSimpleName() + “.” + method.getName() + “.” + Arrays.toString(params);

log.info(“Cache key suffix : {}”, keySuffix);

return keySuffix;

}

}

接着配置注册为 Bean:

@Configuration

public class CustomConfig {

@Bean

public CustomKeyGenerator customKeyGenerator() {

return new CustomKeyGenerator();

}

}

编写 Service 用于测试,具体的测试代码这里就不再贴出来了,有兴趣的可以自行尝试。

@Slf4j

@Service

@CacheConfig(cacheNames = “user”)

public class UserSupportService {

@Resource

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 可以通过集成Spring Data Redis添加Redis缓存。Spring Data RedisSpring提供的一个用于操作Redis的开源库。要添加Redis缓存,可以按照以下几个步骤进行操作。 第一步,添加依赖: 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 这将自动引入Spring Data Redis及其相关依赖。 第二步,配置Redis连接信息: 在application.properties(或application.yml)文件中配置Redis连接信息,如下所示: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.database=0 ``` 可以根据实际情况修改Redis的主机名、端口号、密码和数据库索引。 第三步,使用Redis缓存: 在需要使用Redis缓存的地方,可以使用Spring提供的注解进行缓存操作。例如,可以使用`@Cacheable`注解标记一个方法,表示该方法的结果将被缓存: ```java @Cacheable("myCache") public String getValue(String key) { // 从数据库或其他数据源中获取数据 return value; } ``` 在上面的例子中,`myCache`是缓存的名称,可以根据实际需要进行命名。当调用`getValue`方法时,如果缓存中已经有对应的数据,则直接从缓存中获取数据,否则会执行方法体内的代码,并将结果缓存起来。 需要注意的是,为了使`@Cacheable`注解生效,还需要在启动类上添加`@EnableCaching`注解,以启用缓存功能。 通过以上步骤,就可以在Spring Boot应用添加Redis缓存,并使用Redis作为数据的缓存存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值