玩转spring boot——结合redis

前言


 

  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>
pom.xml

 

修改入口类文件“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);
    }
}
App.java

 

添加控制器“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;
    }

}
MainController.java

 

新建模板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>
index.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
     */
}
Order

注意,一定要实现“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;
    }
}
OrderDao.java

在方法“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>
index.html

 

 

运行效果:

 

 

第一遍查询生成当前时间,之后再查询则时间不变

 

 

代码:https://github.com/carter659/spring-boot-08.git

 

 

如果你觉得我的博客对你有帮助,可以给我点儿打赏,左侧微信,右侧支付宝。

有可能就是你的一点打赏会让我的博客写的更好:)

 

玩转spring boot系列目录

posted @ 2017-01-04 13:23  冬子哥  阅读(2056)  评论(3编辑  收藏  举报