springboot using Redis (II. Use of Spring Data Redis)

Use springboot redis operation has three kinds of programs

1.Spring Cache
2. Spring Data Redis
3. Jedis

The second method of this article say: Spring Data Redis

Springboot on an article about the use of Spring Cache operation redis, in most cases, because there are some limitations annotation is not flexible enough, the actual development is generally used in String Data Redis.

1. pom.xml

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.application.properties

#redis
spring.redis.port=6379
spring.redis.host=localhost

3. The manner of operation redis

spring Data Redis Redis provides two methods of operation:

  • RedisTemplate
  • StringRedisTemplate

RedisTemplate used by default jdk serialized manner, stored in redis Key and Value are the binary is stored in the redis difficult to read .

StringRedisTemplate defaults StringRedisSerializer , Key and Value is the key to type easier to read

Use StringRedisTemplate , save data to redis

	@Autowired
    private StringRedisTemplate redisClient;
		//opsForValue:用来设置最简单的key-value对操作
        redisClient.opsForValue().set("test","hello");
        String stra = redisClient.opsForValue().get("test");
        System.out.println(stra);
        //opsForList:操作List结构
        redisClient.opsForList().leftPush("message","hello1");
        redisClient.opsForList().leftPush("message","hello2");
        List list = new ArrayList();
        list = redisClient.opsForList().range("message",0,1);
        System.out.println(list);
        //opsForHash:用来操作hash结构
        redisClient.opsForHash().put("cache","key","value");
        System.out.println(redisClient.opsForHash().get("cache","key"));

        //opsForXXX每次都要输入Key作为第一个参数,你也可以通过RedisTemplates提供的				  boundXXXOps()来指定一个Key,
        //返回BoundXXXOperations。这样在BoundXXXOperation上的操作就不需要提供Key作为参数
        BoundListOperations operations = redisClient.boundListOps("somekey");
        operations.leftPush("a");
        operations.leftPush("b");
        System.out.println(operations.size());
        redisClient.opsForValue().set("age","18");

redis console and display data
Here Insert Picture DescriptionHere Insert Picture Description

4. Spring Data Redis cumbersome than Spring Cache

Because using Spring Data Redis cache operations redis do so, to go through several steps:

  • Data Query database
  • The query to the data put in redis

Spring Cache used then used directly @Cacheable directly into the return value in redis

So use Spring Cache simple point, but there are some limitations due to the notes is not flexible enough, so it according to their own choice, in the development of these two methods commonly used, and jedis way Spring boot in rarely used.

Published 33 original articles · won praise 1 · views 2049

Guess you like

Origin blog.csdn.net/m0_45025658/article/details/104248393