码迷,mamicode.com
首页 > 编程语言 > 详细

SpringCloud+MyBatis+Redis整合—— 超详细实例(二)

时间:2018-08-16 14:55:32      阅读:402      评论:0      收藏:0      [点我收藏+]

标签:.com   整合   通过   print   并且   inf   bsp   control   ring   

2、SpringCloud+MyBatis+Redis

  redis是一种nosql数据库,以键值对<key,value>的形式存储数据,其速度相比于MySQL之类的数据库,相当于内存读写与硬盘读写的差别,所以常常用作缓存,用于少写多读的场景下,直接从缓存拿数据比从数据库(数据库要I/O操作)拿要快得多。
  话不多说,接下来紧接上一章《SpringCloud+MyBatis+Redis整合—— 超详细实例(一)》搭建SpringCloud+MyBatis+Redis环境:

  • 第一步:在pom.xml文件中添加
1       <!-- Redis缓存整合开始 -->
2         <dependency>
3             <groupId>org.springframework.boot</groupId>
4             <artifactId>spring-boot-starter-data-redis</artifactId>
5         </dependency>    
6         <!-- Redis缓存整合结束 -->

技术分享图片

打开一个 cmd 窗口 使用cd命令切换目录到  F:\dev-space\workspaces\newPlatform-2018\RedisForWindow  运行 redis-server.exe redis.windows.conf 。(放文件的实际路径)技术分享图片

第三步:改造controller类,新增Service类让方法拥有Redis缓存

 1 @Service
 2 public class UserService {
 3     @Autowired
 4     private UserMapper userMapper;
 5     
 6     @Cacheable(value="user", key="‘user‘")
 7     public User selectByPrimaryKey(Integer id) {
 8         System.out.println("开始查询.....");
 9         try {
10             Thread.sleep(3 * 1000l);
11         } catch (InterruptedException e) {
12             e.printStackTrace();
13         }
14         System.out.println("查询结束......");
15         User user=userMapper.selectByPrimaryKey(id);
16 
17         return user;
18     }
19     
20 }
 1 @RestController
 2 public class HelloController {
 3     @Autowired
 4     private UserService userService;
 5     
 6     @RequestMapping("/hello")
 7     public String index() {
 8         long beginTime=System.currentTimeMillis();
 9         User  user = userService.selectByPrimaryKey(1);
10         long time=System.currentTimeMillis()-beginTime;
11         return "Hello SpringBoot"+user.getName()+",消耗查询时间:"+time;
12         
13     }
14     
15     
16 }

 

  • 第四步:在页面输入http://127.0.0.1:1111/hello,第一次可以看到通过查询并延迟三秒

技术分享图片

当第二次输入后,该查询会从Redis缓存中获取,所以时间没有延迟三秒,并且非常迅速

技术分享图片

从cmd中  该目录下输入 redis-cli       get user得到:

技术分享图片

说明该对象以存入Redis缓存当中。

至此,SpringCloud+MyBats+Redis搭建成功!

SpringCloud+MyBatis+Redis整合—— 超详细实例(二)

标签:.com   整合   通过   print   并且   inf   bsp   control   ring   

原文地址:https://www.cnblogs.com/king-brook/p/9487078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!