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

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搭建成功!

猜你喜欢

转载自www.cnblogs.com/king-brook/p/9487078.html