Spring Boot系列教程九:Spring boot集成Redis
一.创建项目
项目名称为 “springboot_redis”,创建过程中勾选 “Web”,“Redis”,第一次创建Maven需要下载依赖包(耐心等待)
二.实现
properties配置文件中添加配置信息
1 ##########redis############ 2 3 #redis的IP地址 4 spring.redis.host=localhost 5 #redis的端口 6 spring.redis.port=6379 7 #redis的密码 8 spring.redis.password=123456 9 #redis默认有16个数据库,使用DB0 10 spring.redis.database=0
创建RedisComponent类
1 package com.woniu.RedisComponent; 2 3 import org.apache.hadoop.mapred.gethistory_jsp; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.data.redis.core.StringRedisTemplate; 6 import org.springframework.data.redis.core.ValueOperations; 7 import org.springframework.stereotype.Component; 8 9 10 @Component 11 public class RedisComponent { 12 @Autowired 13 private StringRedisTemplate stringRedisTemplate; 14 15 public void set(String key, String value){ 16 ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue(); 17 boolean bExistent = this.stringRedisTemplate.hasKey(key); 18 if (bExistent) { 19 System.out.println("this key is bExistent!"); 20 }else{ 21 ops.set(key, value); 22 } 23 } 24 25 public String get(String key){ 26 return this.stringRedisTemplate.opsForValue().get(key); 27 } 28 29 public void del(String key){ 30 this.stringRedisTemplate.delete(key); 31 } 32 }
创建WebController类
1 package com.woniu.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.web.bind.annotation.PathVariable; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RestController; 7 8 import com.woniu.RedisComponent.RedisComponent; 9 10 @RestController 11 @RequestMapping(value="/web") 12 public class WebController { 13 14 @Autowired 15 private RedisComponent redisComponet; 16 17 @RequestMapping(value="/set/{key}/{value}") 18 public String set(@PathVariable String key, @PathVariable String value){ 19 redisComponet.set(key, value); 20 return "set key succ!"; 21 } 22 23 @RequestMapping(value="/get/{key}") 24 public String get(@PathVariable String key){ 25 return redisComponet.get(key); 26 } 27 28 @RequestMapping(value="/del/{key}") 29 public void del(@PathVariable String key){ 30 redisComponet.del(key); 31 } 32 }
本机安装redis,设置密码为123456,启动redis。
测试: