项目集成篇:springboot集成redistemple实现自定义缓存,并且可以设置过期时间

在Spring Boot中集成Redis并使用`RedisTemplate`实现自定义缓存功能,同时能够设置缓存项的过期时间,可以通过以下步骤来完成。我们将创建一个服务层方法,该方法将使用`RedisTemplate`直接与Redis交互,并为每个缓存项设置特定的过期时间。

1. 添加依赖

确保你的`pom.xml`文件中有如下依赖:

```xml

<dependencies>

<!-- Spring Boot Starter Web -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- Spring Boot Starter Data Redis -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

<!-- Lombok (Optional) for reducing boilerplate code -->

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

<!-- Test dependencies -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

```

2. 配置Redis连接

编辑`application.properties`或`application.yml`文件以包含Redis的连接信息。

`application.properties`

```properties

Redis server configuration

spring.redis.host=localhost

spring.redis.port=6379

```

或者使用`application.yml`

```yaml

spring:

redis:

host: localhost

port: 6379

```

3. 配置RedisTemplate Bean

为了更灵活地操作Redis,我们需要配置一个`RedisTemplate` bean,并指定序列化方式(如JSON序列化)以便更好地处理复杂对象。

```java

package com.example.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration

public class RedisConfig {

@Bean

public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {

RedisTemplate<String, Object> template = new RedisTemplate<>();

template.setConnectionFactory(connectionFactory);

template.setKeySerializer(new StringRedisSerializer());

template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

return template;

}

}

```

4. 创建自定义缓存服务

接下来,创建一个服务类,它将使用`RedisTemplate`来执行缓存操作,并为每个缓存项设置过期时间。

```java

package com.example.service;

import com.example.model.User;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service

@Slf4j

public class CustomCacheService {

private static final String CACHE_PREFIX = "custom_cache:";

@Autowired

private RedisTemplate<String, Object> redisTemplate;

/**

* 将对象存储到Redis缓存,并设置过期时间

*/

public void cacheObject(String key, Object value, long timeout, TimeUnit timeUnit) {

String cacheKey = CACHE_PREFIX + key;

log.info("Caching object with key: {}", cacheKey);

redisTemplate.opsForValue().set(cacheKey, value, timeout, timeUnit);

}

/**

* 从Redis缓存中获取对象

*/

public Object getObjectFromCache(String key) {

String cacheKey = CACHE_PREFIX + key;

log.info("Fetching object from cache with key: {}", cacheKey);

return redisTemplate.opsForValue().get(cacheKey);

}

/**

* 删除缓存中的对象

*/

public void evictObjectFromCache(String key) {

String cacheKey = CACHE_PREFIX + key;

log.info("Evicting object from cache with key: {}", cacheKey);

redisTemplate.delete(cacheKey);

}

}

```

5. 使用自定义缓存服务

现在可以在控制器或其他服务层中使用`CustomCacheService`来进行缓存操作了。

```java

package com.example.controller;

import com.example.model.User;

import com.example.service.CustomCacheService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping("/api/cache")

@Slf4j

public class CacheController {

@Autowired

private CustomCacheService customCacheService;

@PostMapping("/store")

public String storeUserInCache(@RequestParam String key, @RequestBody User user, @RequestParam long expireSeconds) {

customCacheService.cacheObject(key, user, expireSeconds, TimeUnit.SECONDS);

return "User cached successfully!";

}

@GetMapping("/fetch/{key}")

public Object fetchUserFromCache(@PathVariable String key) {

return customCacheService.getObjectFromCache(key);

}

@DeleteMapping("/evict/{key}")

public String evictUserFromCache(@PathVariable String key) {

customCacheService.evictObjectFromCache(key);

return "User evicted from cache!";

}

}

```

6. 创建实体类(如果需要)

根据你的需求创建实体类,例如`User.java`:

```java

package com.example.model;

import lombok.AllArgsConstructor;

import lombok.Data;

import lombok.NoArgsConstructor;

@Data

@NoArgsConstructor

@AllArgsConstructor

public class User {

private Integer id;

private String name;

private String email;

}

```

注意事项

  • 确保你的Redis服务器正在运行并且可以从应用程序访问。

  • 如果你在本地开发,请确保Redis服务已正确安装并在默认端口6379上运行。

  • 根据实际情况调整包名、路径以及其他细节。

  • 对于生产环境,建议配置Redis连接池、密码认证以及持久化选项等。

通过这种方式,你可以利用`RedisTemplate`实现更加灵活和强大的缓存管理,包括设置每个缓存项的过期时间。如果有任何问题或需要进一步的帮助,请随时提问!

相关推荐
石榴树下9 分钟前
00. 马里奥的 OAuth 2 和 OIDC 历险记
后端
uhakadotcom9 分钟前
开源:subdomainpy快速高效的 Python 子域名检测工具
前端·后端·面试
似水流年流不尽思念26 分钟前
容器化技术了解吗?主要解决什么问题?原理是什么?
后端
Java水解27 分钟前
Java中的四种引用类型详解:强引用、软引用、弱引用和虚引用
java·后端
i听风逝夜28 分钟前
看好了,第二遍,SpringBoot单体应用真正的零停机无缝更新代码
后端
柏油1 小时前
可视化 MySQL binlog 监听方案
数据库·后端·mysql
舒一笑2 小时前
Started TttttApplication in 0.257 seconds (没有 Web 依赖导致 JVM 正常退出)
jvm·spring boot·后端
M1A12 小时前
Java Enum 类:优雅的常量定义与管理方式(深度解析)
后端
AAA修煤气灶刘哥3 小时前
别再懵了!Spring、Spring Boot、Spring MVC 的区别,一篇讲透
后端·面试
189228048613 小时前
NY243NY253美光固态闪存NY257NY260
大数据·网络·人工智能·缓存