[SpringBoot Series 2] SpringBoot integrates Redis

Foreword:

Really like SpringBoot more and more, this is one of the SpringBoot learning series.

text:

1: First add dependencies in the pom file, remember that it is spring-boot-starter-data-redis, not spring-boot-starter-redis

1 <!-- redis -->
2 <dependency>
3     <groupId>org.springframework.boot</groupId>
4     <artifactId>spring-boot-starter-data-redis</artifactId>
5 </dependency>

2: The second step is to configure the data source in the properties file

1 # redis
2 spring.redis.host=120.78.159.xxx
3 spring.redis.port=xxxx
4 spring.redis.password=xxxx

3: The third step is to inject directly

1 @Autowired
2 StringRedisTemplate redis;

Isn't it cool? I was stunned when I used it. How can it be so simple and concise? I feel that the great god of the open source community invented the springboot framework.

附上官方的API:https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/StringRedisTemplate.html

usage:

1: Test whether the connection to redis is successful, and take some key values

 1 // 测试redis
 2     @RequestMapping(value = "/testRedis", method = RequestMethod.GET)
 3     public String testRedis() {
 4         
 5         List<String> list = new ArrayList<>();
 6         list.add("k1");
 7         list.add("k2");
 8         list.add("k3");
 9         System.out.println(redis.opsForValue().multiGet(list));
10         
11         return redis.opsForValue().multiGet(list).toString();
12     }

 

2: Test the set data into redis, and set the timeout mechanism

 1 // put key
 2     @RequestMapping(value = "/putRedis/{id}", method = RequestMethod.GET)
 3     public String putRedis(@PathVariable(value = "id") String id) {
 4         
 5         String key = "Test:" + id;
 6         String value = "I Love zxx";
 7         redis.opsForValue().set(key, value);
 8         redis.expire(key, Integer.MAX_VALUE, TimeUnit.SECONDS);
 9         
10         return "put key to Redis";
11     }

 

3: Test get data from redis

1 // get key
2     @RequestMapping(value = "/getRedis/{id}", method = RequestMethod.GET)
3     public String getRedis(@PathVariable(value = "id") String id) {
4         
5         String key = "Test:" + id;
6         System.out.println(redis.opsForValue().get(key));
7         
8         return "get key from redis";
9     }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325207983&siteId=291194637