💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**1. 引入 spring-boot-starter-data-redis** ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` <br/> **2. 配置 Redis 服务信息`application.yml`** ```yml spring: data: redis: host: 127.0.0.1 port: 6379 ``` <br/> **3. 调用模板类访问 Redis 数据库** 常用的模板类有如下两个: * StringRedisTemplate:该模板的 k/v 只能是 String 类型; * RedisTemplate:该模板的 k/v 必须是可序列化的类,可以实现接口`java.io.Serializable`来让类可以被序列化。 ```java @SpringBootTest class RedisApplicationTests { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; /** * Redis的五大数据类型对应的api: * stringRedisTemplate.opsForValue()[String(字符串)] * stringRedisTemplate.opsForList()[List(列表)] * stringRedisTemplate.opsForSet()[Set(集合)] * stringRedisTemplate.opsForHash()[Hash(散列)] * stringRedisTemplate.opsForZSet()[ZSet(有序集合)] */ @Test public void redisTest1() { stringRedisTemplate.opsForValue().set("message01", "Hellow World!"); String message = stringRedisTemplate.opsForValue().get("message01"); System.out.println(message); ///Hellow World! } @Test public void redisTest2() { Student student = new Student(999, "张三", 25); redisTemplate.opsForValue().set("student01", student); Student student2 = (Student) redisTemplate.opsForValue().get("student01"); System.out.println(student2); ///Student(id=999, name=张三, age=25) } } ``` :-: ![](https://img.kancloud.cn/fa/06/fa060a2e222e5b3aa8a06a4f17039482_1760x232.png) ![](https://img.kancloud.cn/ed/9e/ed9e1b137abd71d448fcf10c1bad8ff9_1750x308.png) 存储到 Redis 的数据