目录
1 创建新的模块--选择noSQL:勾选第一个 spring data redis
2 yaml配置
3 测试
注入StringRedisTemplate对象
获取存储结构
设置和获取值
1 创建新的模块--选择noSQL:勾选第一个 spring data redis
或者手动导入依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
2 yaml配置 (默认使用的是lettue客户端实现技术 )
- #不配置也可以,默认就是6379和localhost
- spring:
- redis:
- host: localhost
- port: 6379
3 测试(前提:先启动Redis服务端)
- package com.qing;
-
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.data.redis.core.HashOperations;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import org.springframework.data.redis.core.ValueOperations;
-
- @SpringBootTest
- class SpringbootRedisApplicationTests {
-
- @Autowired
- //RedisTemplate不写泛型key是Object,不能操作Redis客户端
- //private RedisTemplate redisTemplate;
- //1 注入StringRedisTemplate对象,能操作redis客户端,数据会更新客户端
- private StringRedisTemplate redisTemplate;
-
-
- @Test
- void setTest() {
- //2 获取基本存储结构key-value
- ValueOperations<String, String> ops = redisTemplate.opsForValue();
- //3 设置值
- ops.set("brother","kiki");
- }
- @Test
- void getTest() {
-
- ValueOperations ops = redisTemplate.opsForValue();
- //获取值
- Object age = ops.get("brother");
- System.out.println(age);
- }
- @Test
- void hsetTest() {
- //2 获取hash存储结构
- HashOperations<String, Object, Object> hOps = redisTemplate.opsForHash();
- //3 设置值
- hOps.put("info","name","Joblaue");
- hOps.put("info","sex","girl");
- }
- @Test
- void hgetTest() {
-
- HashOperations<String, Object, Object> hOps = redisTemplate.opsForHash();
- // 获取值
- Object name = hOps.get("info", "name");
- Object sex = hOps.get("info", "sex");
- System.out.println(name+":"+sex);
- }
-
- }
结果
1 导入依赖
2 修改配置文件 client-type为jedis