前言
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
如果你覺得我的博客對你有幫助,可以給我點兒打賞,左側微信,右側支付寶。
有可能就是你的一點打賞會讓我的博客寫的更好:)