第一步:pom.xml文件导入坐标
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.5.4</version> </dependency
第二步:application.yml文件添加配置
spring: redis: host: localhost port: 6379
第三步:RedisTemplate 提供操作各种数据存储类型的接口API
默认就是object 的类型
@SpringBootTest public class RedisTest { @Autowired private RedisTemplate redisTemplate; @Test public void testsetKeys(){ ValueOperations ops = redisTemplate.opsForValue(); ops.set("name","minkl1"); ops.set("country","china"); } @Test public void testgetKeys(){ ValueOperations ops = redisTemplate.opsForValue(); System.out.println(ops.get("name")); System.out.println(ops.get("country")); }
@Test public void testHashsetKeys() { HashOperations hashOperations = redisTemplate.opsForHash(); hashOperations.put("keya", "local1", "china"); hashOperations.put("keya", "local2", "chinaeasdf"); hashOperations.put("keya", "local3", "chifdsaf"); } @Test public void testHashgetKeys(){ HashOperations hashOperations = redisTemplate.opsForHash(); System.out.println(hashOperations.get("keya", "local1")); System.out.println(hashOperations.get("keya", "local2")); System.out.println(hashOperations.get("keya", "local3")); }
}
缺点:代码执行的结果,在redis客户端找不到??这就不是很友好
客户端建立的键值对,代码也读取不出来??
第四步:操作升级--带string 泛型,字符串类型
private StringRedisTemplate stringRedisTemplate;//字符串类型---redis--可以实现代码和客户端操作互通
@ContextConfiguration(classes = Application.class) @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class StringRedisTest { // private RedisTemplate redisTemplate;//泛型没有带数据类型,默认就是object 的类型 @Autowired private StringRedisTemplate stringRedisTemplate;//字符串类型---redis @Test public void test(){ ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue(); System.out.println(stringStringValueOperations.get("name")); } @Test public void testSet(){ ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue(); stringStringValueOperations.set("name","不是666啦"); } }