SpringBoot 整合 Redis 的简单案例

释放双眼,带上耳机,听听看~!

Redis
今天看了redis, 只知道redis能做3件事:

做缓存
做非关系型数据库
做消息中间件

一、安装Redis

Window 下安装 下载地址:https://github.com/MSOpenTech/redis/releases。 Redis
支持32 位和64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.zip压缩包到
C盘的tools目录中,解压后,将文件夹重新命名为 redis。

打开一个 cmd 窗口 使用cd命令切换目录到 C:\tools\redis 运行 redis-server.exe
redis.windows.conf 。

redis启动指令:1.cd 进入 redis目录下;2.redis-server.exe redis.windows.conf
(用redis.windows.conf配置文件启动redis)

redis登录指令: redis-cli.exe -h host -p port -a password
(redis访问默认不需要密码)Redis密码设置 设置密码:config set requirepass(密码) 密码验证:config
get requirepass 在redis.windows.conf文件中设置 requirepass 密码

退出redis shutdown exit
安装成功后,可以在windows的服务管理中对redis进行管理,就不用每次都打开命令窗口来启动redis服务了,如下图:

二、在原有项目中引入redis,先在pom.xml添加redis的依赖


1
2
3
4
5
6
7
1<!-- 添加redis -->  
2<dependency>
3   <groupId>org.springframework.boot</groupId>
4   <artifactId>spring-boot-starter-redis</artifactId>
5   <version>1.4.5.RELEASE</version>
6</dependency>
7

三、在application.properties中添加redis配置信息


1
2
3
4
5
6
7
8
9
10
11
1#redis config
2spring.redis.database=0
3spring.redis.host=127.0.0.1
4spring.redis.port=6379
5spring.redis.password=
6spring.redis.pool.max-active=8
7spring.redis.pool.max-wait=-1
8spring.redis.pool.max-idle=8
9spring.redis.pool.min-idle=0
10spring.redis.timeout=0
11

四、新建一个config包,用来存放一些配置文件,新建RedisConfig.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
1package com.hsp.config;
2
3import org.springframework.cache.CacheManager;
4import org.springframework.cache.annotation.CachingConfigurerSupport;
5import org.springframework.cache.annotation.EnableCaching;
6import org.springframework.context.annotation.Bean;
7import org.springframework.context.annotation.Configuration;
8import org.springframework.data.redis.cache.RedisCacheManager;
9import org.springframework.data.redis.connection.RedisConnectionFactory;
10import org.springframework.data.redis.core.RedisTemplate;
11
12@Configuration  
13@EnableCaching//开启注解  
14public class RedisConfig extends CachingConfigurerSupport {
15    @Bean
16    public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) {
17       CacheManager cacheManager = new RedisCacheManager(redisTemplate);
18       return cacheManager;
19    }
20
21    @Bean
22    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
23       RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
24       redisTemplate.setConnectionFactory(factory);
25       return redisTemplate;
26    }
27}
28

六、在service包中建立一个RedisService.java类


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
1package com.yjy.service;
2
3/**
4 *
5 * Description:
6 *
7 * @author
8 * @since JDK1.8
9 * @history 2018年9月4日
10 */
11public interface RedisService {
12
13    /**
14    * Description:指定缓存失效时间
15    * @param    key 键
16    * @param    time 时间(秒)
17    * @return   boolean
18    */
19    public boolean expire(String key,long time);
20
21    /**
22    * Description:根据key 获取过期时间
23    * @param    key 键 不能为null
24    * @return   时间(秒) 返回0代表为永久有效
25    */
26    public long getExpire(String key);
27
28    /**
29    * Description:判断key是否存在
30    * @param    key 键
31    * @return   true 存在 false不存在
32    */
33    public boolean hasKey(String key);
34
35
36    /**
37    * Description:普通缓存放入
38    * @param    key 键
39    * @param    value 值
40    * @return   true成功 false失败
41    */
42    public void set(String key, Object value);
43
44    /**
45    * Description:普通缓存获取
46    * @param    key 键
47    * @return   值
48    */
49    public Object get(String key);
50
51    /**
52    * Description:删除缓存
53    * @param    key 可以传一个值 或多个
54    * @return
55    */
56    public void del(String ... key);
57}
58

七、RedisServiceImpl.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
1package com.yjy.service.impl;
2
3import java.util.concurrent.TimeUnit;
4import javax.annotation.Resource;
5import org.springframework.data.redis.core.RedisTemplate;
6import org.springframework.data.redis.core.ValueOperations;
7import org.springframework.stereotype.Service;
8import org.springframework.util.CollectionUtils;
9import com.yjy.service.RedisService;
10
11/**
12 *
13 * Description:
14 *
15 * @author
16 * @since JDK1.8
17 * @history 2018年9月4日
18 */
19@Service
20public class RedisServiceImpl implements RedisService{
21
22    @Resource
23    private RedisTemplate<String,Object> redisTemplate;
24
25    @Override
26    public void set(String key, Object value) {
27        ValueOperations<String,Object> vo = redisTemplate.opsForValue();
28        vo.set(key, value);
29    }
30
31    @Override
32    public Object get(String key) {
33        ValueOperations<String,Object> vo = redisTemplate.opsForValue();
34        return vo.get(key);
35    }
36
37    @Override
38    public boolean expire(String key, long time) {
39        try {  
40            if(time>0){  
41                redisTemplate.expire(key, time, TimeUnit.SECONDS);  
42            }  
43            return true;  
44        } catch (Exception e) {  
45            e.printStackTrace();  
46            return false;  
47        }  
48    }
49
50    @Override
51    public long getExpire(String key) {
52        return redisTemplate.getExpire(key,TimeUnit.SECONDS);  
53    }
54
55    @Override
56    public boolean hasKey(String key) {
57        try {  
58            return redisTemplate.hasKey(key);  
59        } catch (Exception e) {  
60            e.printStackTrace();  
61            return false;  
62        }  
63    }
64
65    @Override
66    public void del(String... key) {
67        if(key!=null&&key.length>0){  
68            if(key.length==1){  
69                redisTemplate.delete(key[0]);  
70            }else{  
71                redisTemplate.delete(CollectionUtils.arrayToList(key));  
72            }  
73        }  
74    }  
75}
76

八、StartApplication.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
1package com.yjy.controller;
2
3import org.mybatis.spring.annotation.MapperScan;
4import org.springframework.boot.SpringApplication;
5import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
6import org.springframework.boot.autoconfigure.SpringBootApplication;
7import org.springframework.cache.annotation.EnableCaching;
8import org.springframework.transaction.annotation.EnableTransactionManagement;
9
10/**
11 *
12 * Description:
13 *
14 * @author
15 * @since JDK1.8
16 * @history 2018年8月30日 新建
17 */
18@SpringBootApplication(scanBasePackages = {"com.yjy.controller","com.yjy.service.impl","com.yjy.config"})
19@EnableCaching //开启缓存
20@EnableTransactionManagement // 开启事务管理
21@EnableAutoConfiguration
22//  配置mapper层的扫描
23@MapperScan(basePackages = {"com.yjy.mapper"})
24public class StartApplication {
25    public static void main(String[] args) {
26        SpringApplication.run(StartApplication.class, args);
27    }
28}
29

九、GoodsController.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
1package com.yjy.controller;
2
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.stereotype.Controller;
5import org.springframework.web.bind.annotation.RequestMapping;
6import org.springframework.web.bind.annotation.RequestParam;
7import org.springframework.web.bind.annotation.ResponseBody;
8import com.yjy.pojo.Goods;
9import com.yjy.service.GoodsService;
10import com.yjy.service.RedisService;
11
12/**
13 *
14 * Description:
15 *
16 * @author
17 * @since JDK1.8
18 * @history 2018年8月30日 新建
19 */
20@Controller
21public class GoodsController {
22    @Autowired
23    private GoodsService goodsService;
24
25    @Autowired
26    private RedisService redisService;
27
28    @RequestMapping("/selectBy.do")
29    @ResponseBody
30    public Goods selectBy(String name,int num) {
31        Goods goods = goodsService.selectBy(name,num);
32        redisService.set(goods.getId()+"", goods);
33        redisService.expire(goods.getId()+"", 60);
34        return  goods;
35    }
36
37    //  通过key获取value
38    @RequestMapping("/getgoodsfromredis.do")
39    @ResponseBody
40    public Goods getRedis(@RequestParam String key) {
41        return (Goods) redisService.get(key);
42    }
43
44    //  根据key获取缓存过期时间
45    @RequestMapping("/getTime.do")
46    @ResponseBody
47    public long getExpire(@RequestParam String key) {
48        return redisService.getExpire(key);
49    }
50
51    //  根据key删除缓存
52    @RequestMapping("/delRediskey.do")
53    @ResponseBody
54    public void del(@RequestParam String ... key) {
55        redisService.del(key);
56    }      
57}
58

十、测试

成功存入Redis

给TA打赏
共{{data.count}}人
人已打赏
安全运维

OpenSSH-8.7p1离线升级修复安全漏洞

2021-10-23 10:13:25

安全运维

设计模式的设计原则

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索