1. 程式人生 > >【SpringBoot系列2】SpringBoot整合Redis

【SpringBoot系列2】SpringBoot整合Redis

並且 nds key值 數據 配置數據源 eth ren core 成功

前言:

真的越來越喜歡SpringBoot了,這是SpringBoot學習系列之一。

正文:

1:首先在pom文件中添加依賴,記得是spring-boot-starter-data-redis,不是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:第二步在properties文件中配置數據源

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

3: 第三步,直接註入即可

1 @Autowired
2 StringRedisTemplate redis;

是不是很爽,我用的時候被驚呆了,怎麽可以這麽簡單,這麽簡潔,太感覺開源社區的大神發明了springboot這個框架。

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

用法:

1:測試是否連接redis成功,並且取一些key值出來

 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:測試set數據進redis,並且設置超時機制

 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: 測試從redis裏面get數據出來

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     }

【SpringBoot系列2】SpringBoot整合Redis