SpringBoot integrates redis and StringRedisTemplate to operate redis

  1. pom.xml 加入 spring-boot-starter-data-redis
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. application.yml configuration hostname
spring:
  redis:
    host: localhost
  1. Use RedisTemplate<Object, Object> to write the test code for the test class. Because of this inconvenient use, the object type will be serialized.
@Autowired // 自动注入redisTemplate 针对对象型的
RedisTemplate<Object, Object> redisTemplate;
@Test
public void test(){
    // 获取用来操作string类型的ValueOperations对象
    ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();

    // 设置key value
    valueOperations.set("mywife", "gaomei");

    // 通过key获取value
    Object object = valueOperations.get("mywife");
    System.out.println(object);

}
  1. Test class write test code Use StringRedisTemplate
    4.1 StringRedisTemplate to manipulate string type values
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
public void test1(){
    // 操作Value为string类型的数据
    ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
    valueOperations.set("myson", "quyuchen");
    Object object1 = valueOperations.get("myson");
    System.out.println(object1);
}

4.2 StringRedisTemplate operation list type value

@Test
public void test2(){
    // 操作Value为string类型的数据
    ListOperations<String, String> listOperations = stringRedisTemplate.opsForList();
    // 给list里面塞值
    listOperations.leftPush("aaa", "aaa");
    listOperations.leftPush("aaa", "bbb");
    listOperations.leftPush("aaa", "ccc");
    listOperations.leftPush("aaa", "ddd");

    // 通过range方法获取list列表
    List<String> list = listOperations.range("aaa", 0, -1);
    System.out.println(list);
}

Guess you like

Origin blog.csdn.net/q18729096963/article/details/105693436