当前位置: 首页 > news >正文

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@Beanpublic 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序列化方式采用jacksontemplate.setValueSerializer(jackson2JsonRedisSerializer);// hash的value序列化方式采用jacksontemplate.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;@Autowiredpublic 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;@Autowiredpublic 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);}
}

http://www.mrgr.cn/news/75006.html

相关文章:

  • 大数据新视界 -- 大数据大厂之 Impala 性能飞跃:动态分区调整的策略与方法(上)(21 / 30)
  • Python 的 Pygame 库,编写简单的 Flappy Bird 游戏
  • 万字长文解读深度学习——卷积神经网络CNN
  • gitlab角色、权限
  • uniapp使用scroll-view下拉刷新与上滑加载
  • 搭建Python2和Python3虚拟环境
  • 得物精准测试平台设计与实现
  • ros1 noetic跑UR5_gripper_camera_gazebo
  • Android Framework AMS(16)进程管理
  • Excel筛选的操作教程
  • QEMU 模拟器中运行的 Linux 系统
  • Elasticsearch 重建索引 数据迁移
  • PVE纵览-构建可靠的虚拟化平台:Proxmox VE高可用性详解
  • 开关电源漏电流测试需要哪些特殊设备?-纳米软件
  • golang将word、excel转换为pdf
  • 1990-2020年中国人工林和天然林空间分布数据集
  • SwiftUI 高级开发教程系列 - 第 3 章:数据持久化
  • 【Android】Android滑动冲突解决方案
  • 异构迁移常用SQL
  • 【Go 开发】pprof 排查问题流程:排查程序 CPU 占用高的问题
  • Android Mobile Network Settings | APN 菜单加载异常
  • 解密复杂系统:理论、模型与案例(3)
  • 计算机网络(7)
  • 山泽光纤HDMI线:铜线的隐藏力量
  • 《人类简史:从动物到上帝》读书笔记
  • Redhat7.9 安装 KingbaseES 金仓数据库 V9单机版(静默安装)