Spring Boot 应用程序中集成 Redis 并实现存储读取字符串或者复杂对象
步骤如下:
1. 添加依赖
确保你的 pom.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>
<!-- Jackson for JSON serialization/deserialization -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Lombok (可选) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
2. 配置 Redis
在 application.properties 文件中配置 Redis 连接信息:
spring.redis.host=localhost
spring.redis.port=6379
3. 配置 RedisTemplate
创建一个配置类来配置 RedisTemplate,以便支持多种数据类型的序列化和反序列化:
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@Configuration
public class RedisConfig {
@Bean
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//LocalDatetime序列化
JavaTimeModule timeModule = new JavaTimeModule();
timeModule.addDeserializer(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
timeModule.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
timeModule.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
timeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
om.registerModule(timeModule);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
4. 创建 Redis 服务类
创建一个服务类来封装 Redis 操作,支持多种数据类型:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Map;
@Service
public class RedisService {
private final RedisTemplate<String, Object> redisTemplate;
@Autowired
public RedisService(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
// 存储字符串
public void setString(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
// 获取字符串
public String getString(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
// 存储对象
public void setObject(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
// 获取对象
public <T> T getObject(String key, Class<T> clazz) {
return clazz.cast(redisTemplate.opsForValue().get(key));
}
// 存储列表
public void setList(String key, List<Object> list) {
redisTemplate.opsForList().rightPushAll(key, list);
}
// 获取列表
public List<Object> getList(String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
// 存储集合
public void setSet(String key, Set<Object> set) {
redisTemplate.opsForSet().add(key, set.toArray());
}
// 获取集合
public Set<Object> getSet(String key) {
return redisTemplate.opsForSet().members(key);
}
// 存储哈希表
public void setHash(String key, Map<Object, Object> map) {
redisTemplate.opsForHash().putAll(key, map);
}
// 获取哈希表
public Map<Object, Object> getHash(String key) {
return redisTemplate.opsForHash().entries(key);
}
// 删除键
public void deleteKey(String key) {
redisTemplate.delete(key);
}
}
5. 创建控制器
创建一个控制器来暴露 REST API,以便客户端可以调用 Redis 操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.Arrays;
import java.util.HashMap;
@RestController
@RequestMapping("/api/redis")
public class RedisController {
private final RedisService redisService;
@Autowired
public RedisController(RedisService redisService) {
this.redisService = redisService;
}
// 设置字符串
@PostMapping("/setString")
public String setString(@RequestParam String key, @RequestParam String value) {
redisService.setString(key, value);
return "Value set successfully";
}
// 获取字符串
@GetMapping("/getString")
public String getString(@RequestParam String key) {
return redisService.getString(key);
}
// 设置对象
@PostMapping("/setObject")
public String setObject(@RequestParam String key, @RequestBody Object value) {
redisService.setObject(key, value);
return "Object set successfully";
}
// 获取对象
@GetMapping("/getObject")
public Object getObject(@RequestParam String key) {
return redisService.getObject(key, Object.class);
}
// 设置列表
@PostMapping("/setList")
public String setList(@RequestParam String key, @RequestBody List<Object> list) {
redisService.setList(key, list);
return "List set successfully";
}
// 获取列表
@GetMapping("/getList")
public List<Object> getList(@RequestParam String key) {
return redisService.getList(key);
}
// 设置集合
@PostMapping("/setSet")
public String setSet(@RequestParam String key, @RequestBody Set<Object> set) {
redisService.setSet(key, set);
return "Set set successfully";
}
// 获取集合
@GetMapping("/getSet")
public Set<Object> getSet(@RequestParam String key) {
return redisService.getSet(key);
}
// 设置哈希表
@PostMapping("/setHash")
public String setHash(@RequestParam String key, @RequestBody Map<Object, Object> map) {
redisService.setHash(key, map);
return "Hash set successfully";
}
// 获取哈希表
@GetMapping("/getHash")
public Map<Object, Object> getHash(@RequestParam String key) {
return redisService.getHash(key);
}
// 删除键
@DeleteMapping("/deleteKey")
public String deleteKey(@RequestParam String key) {
redisService.deleteKey(key);
return "Key deleted successfully";
}
}
6. 启动类
创建一个启动类来启动 Spring Boot 应用程序:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}