前言
Redis 是一個高效能的key-value資料庫。 redis的出現,很大程度補償了memcached這類key/value儲存的不足,在部 分場合可以對關聯式資料庫起到很好的補充作用。它提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客戶端,使用很方便。使用redis有兩種場景:1.快取。2.高熱資料儲存(無非還是快取),彌補關係型資料庫的不足。
一、準備工作
下載redis的windows版zip包:https://github.com/MSOpenTech/redis/releases
執行redis-server.exe程式
出現黑色視窗表示redis服務已啟動。
二、與spring boot結合
參考官方例子:http://spring.io/guides/gs/messaging-redis/
修改pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.carter659</groupId> <artifactId>spring08</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> </parent> <name>spring08</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
修改入口類檔案“App.java”:
package com.github.carter659.spring08; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * @author 劉冬 * */ @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } }
新增控制器“MainController.java”檔案:
package com.github.carter659.spring08; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ @Controller public class MainController { private static final String STR_REDIS_KEY = "key:name"; @Autowired private StringRedisTemplate redisTemplate; @GetMapping("/") public String index() { return "index"; } @PostMapping("/setString") public @ResponseBody Map<String, Object> setString(String value) { redisTemplate.opsForValue().set(STR_REDIS_KEY, value); Map<String, Object> map = new HashMap<>(); map.put("msg", "ok"); return map; } @PostMapping("/getString") public @ResponseBody Map<String, Object> getString() { String value = redisTemplate.opsForValue().get(STR_REDIS_KEY); Map<String, Object> map = new HashMap<>(); map.put("value", value); map.put("msg", "ok"); return map; } }
新建模板src/main/resources/templates/index.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>玩轉spring boot——結合redis</title> <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script> <script type="text/javascript"> /*<![CDATA[*/ var app = angular.module('app', []); app.controller('MainController', function($rootScope, $scope, $http) { $scope.value = '劉冬'; //儲存 $scope.setString = function() { $http({ url : '/setString?value=' + $scope.value, method : 'POST' }); } $scope.getString = function() { $http({ url : '/getString', method : 'POST' }).success(function(r) { $scope.result = JSON.stringify(r) }); } }); /*]]>*/ </script> </head> <body ng-app="app" ng-controller="MainController"> <h1>玩轉spring boot——結合redis</h1> <h4> <a href="http://www.cnblogs.com/GoodHelper/">from 劉冬的部落格</a> </h4> <input type="text" ng-model="value" /> <input type="button" value="設定" ng-click="setString()" /> <br /> <br /> <input type="button" value="獲取" ng-click="getString()" /> <br /> <h3>結果:</h3> <p>{{result}}</p> <br /> <a href="http://www.cnblogs.com/GoodHelper/">點選訪問原版部落格</a> </body> </html>
執行效果:
點選獲取,提示未空,再設定:
與redis的簡單結合就實現了。
三、redis快取整合
新增“Order.java”類檔案:
package com.github.carter659.spring08;
import java.io.Serializable;
import java.util.Date;
/**
* 部落格出處:http://www.cnblogs.com/GoodHelper/
*
* @author 劉冬
*
*/
public class Order implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String id;
public String no;
public Date date;
public int quantity;
/**
* 省略 get set
*/
}
注意,一定要實現“Serializable”介面。
新建“OrderDao.java”類檔案:
package com.github.carter659.spring08; import java.util.Date; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ @Component public class OrderDao { /** * 假設從資料庫獲取的訂單資料 * * @param id * @return */ @Cacheable(value = "order", key = "'.id.'+#id") public Order get(String id) { Order order = new Order(); order.id = id; order.no = "No.00001"; order.date = new Date(); order.quantity = 100; return order; } }
在方法“public Order get(String id)”上加“@Cacheable”註解
此方法模擬資料庫的查詢,如果是第一次查詢,返回當前時間(new Date())。如果在快取中查詢,則時間是之前的。
控制器“MainController.java”增加“orderDao”欄位和“get”方法:
@Autowired private OrderDao orderDao;
@PostMapping("/get") public @ResponseBody Order get(@RequestParam String id) { return orderDao.get(id); }
在App類中加入啟動快取的註解“@EnableCaching”:
package com.github.carter659.spring08; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ @SpringBootApplication @EnableCaching public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } }
修改之前的index.html檔案
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>玩轉spring boot——結合redis</title> <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script> <script type="text/javascript"> /*<![CDATA[*/ var app = angular.module('app', []); app.controller('MainController', function($rootScope, $scope, $http) { $scope.value = '劉冬'; $scope.id = '123456'; //儲存 $scope.setString = function() { $http({ url : '/setString?value=' + $scope.value, method : 'POST' }); } $scope.getString = function() { $http({ url : '/getString', method : 'POST' }).success(function(r) { $scope.result = JSON.stringify(r) }); } $scope.getOrder = function() { $http({ url : '/get?id=' + $scope.id, method : 'POST' }).success(function(r) { $scope.result = JSON.stringify(r) }); } }); /*]]>*/ </script> </head> <body ng-app="app" ng-controller="MainController"> <h1>玩轉spring boot——結合redis</h1> <h4> <a href="http://www.cnblogs.com/GoodHelper/">from 劉冬的部落格</a> </h4> <input type="text" ng-model="value" /> <input type="button" value="設定" ng-click="setString()" /> <br /> <br /> <input type="button" value="獲取" ng-click="getString()" /> <br /> <br /> <input type="text" ng-model="id" /> <br /> <input type="button" value="獲取訂單" ng-click="getOrder()" /> <br /> <br /> <h3>結果:</h3> <p>{{result}}</p> <br /> <a href="http://www.cnblogs.com/GoodHelper/">點選訪問原版部落格</a> </body> </html>
執行效果:
第一遍查詢生成當前時間,之後再查詢則時間不變
程式碼:https://github.com/carter659/spring-boot-08.git
如果你覺得我的部落格對你有幫助,可以給我點兒打賞,左側微信,右側支付寶。
有可能就是你的一點打賞會讓我的部落格寫的更好:)