【SpringBoot系列2】SpringBoot整合Redis

前言:

真的越来越喜欢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     }

猜你喜欢

转载自www.cnblogs.com/wenbochang/p/8985717.html