---
title: "Spring Boot使用redis做数据缓存"
author: "xiaowei2002"
date: "2015-07-31T16:31:58Z"
tags: []
categories: ["企业架构"]
slug: "spring-boot-redis"
draft: false
lastmod: "2015-07-31T16:31:58Z"
id: 2231945
url: "https://xiaowei2002.iteye.com/blog/2231945"
---

# 1 添加redis支持

 

在pom.xml中添加

 

Xml代码  [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

1. &lt;dependency&gt;
2. &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
3. &lt;artifactId&gt;spring-boot-starter-redis&lt;/artifactId&gt;
4. &lt;/dependency&gt;

 

 

 

# 2 redis配置

 

Java代码  [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. package com.wisely.ij.config;
02. import com.fasterxml.jackson.annotation.JsonAutoDetect;
03. import com.fasterxml.jackson.annotation.PropertyAccessor;
04. import com.fasterxml.jackson.databind.ObjectMapper;
05. import org.springframework.cache.CacheManager;
06. import org.springframework.cache.annotation.CachingConfigurerSupport;
07. import org.springframework.cache.annotation.EnableCaching;
08. import org.springframework.cache.interceptor.KeyGenerator;
09. import org.springframework.context.annotation.Bean;
10. import org.springframework.context.annotation.Configuration;
11. import org.springframework.data.redis.cache.RedisCacheManager;
12. import org.springframework.data.redis.connection.RedisConnectionFactory;
13. import org.springframework.data.redis.core.RedisTemplate;
14. import org.springframework.data.redis.core.StringRedisTemplate;
15. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
16. import java.lang.reflect.Method;
17. @Configuration
18. @EnableCaching
19. public class RedisConfig extends CachingConfigurerSupport{
20. @Bean
21. public KeyGenerator wiselyKeyGenerator(){
22. return new KeyGenerator() {
23. @Override
24. public Object generate(Object target, Method method, Object... params) {
25. StringBuilder sb = new StringBuilder();
26. sb.append(target.getClass().getName());
27. sb.append(method.getName());
28. for (Object obj : params) {
29. sb.append(obj.toString());
30. }
31. return sb.toString();
32. }
33. };
34. }
35. @Bean
36. public CacheManager cacheManager(
37. @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
38. return new RedisCacheManager(redisTemplate);
39. }
40. @Bean
41. public RedisTemplate&lt;String, String&gt; redisTemplate(
42. RedisConnectionFactory factory) {
43. StringRedisTemplate template = new StringRedisTemplate(factory);
44. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
45. ObjectMapper om = new ObjectMapper();
46. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
47. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON\_FINAL);
48. jackson2JsonRedisSerializer.setObjectMapper(om);
49. template.setValueSerializer(jackson2JsonRedisSerializer);
50. template.afterPropertiesSet();
51. return template;
52. }
53. }

 

 

 

 

 

# 3 redis服务器配置

 

Properties代码  [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. # REDIS (RedisProperties)
02. spring.redis.database= # database name
03. spring.redis.host=localhost # server host
04. spring.redis.password= # server password
05. spring.redis.port=6379 # connection port
06. spring.redis.pool.max-idle=8 # pool settings ...
07. spring.redis.pool.min-idle=0
08. spring.redis.pool.max-active=8
09. spring.redis.pool.max-wait=-1
10. spring.redis.sentinel.master= # name of Redis server
11. spring.redis.sentinel.nodes= # comma-separated list of host:port pairs

 

 

 

# 4 应用

 

测试两个实体类

 

Java代码  [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. package com.wisely.ij.domain;
02. public class Address {
03. private Long id;
04. private String province;
05. private String city;
06. public Address(Long id,String province, String city) {
07. this.id = id;
08. this.province = province;
09. this.city = city;
10. }
11. public Address() {
12. }
13. public Long getId() {
14. return id;
15. }
16. public void setId(Long id) {
17. this.id = id;
18. }
19. public String getProvince() {
20. return province;
21. }
22. public void setProvince(String province) {
23. this.province = province;
24. }
25. public String getCity() {
26. return city;
27. }
28. public void setCity(String city) {
29. this.city = city;
30. }
31. }

 

 

 

Java代码  [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. package com.wisely.ij.domain;
02. public class User {
03. private Long id;
04. private String firstName;
05. private String lastName;
06. public User(Long id,String firstName, String lastName) {
07. this.id = id ;
08. this.firstName = firstName;
09. this.lastName = lastName;
10. }
11. public User() {
12. }
13. public Long getId() {
14. return id;
15. }
16. public void setId(Long id) {
17. this.id = id;
18. }
19. public String getFirstName() {
20. return firstName;
21. }
22. public void setFirstName(String firstName) {
23. this.firstName = firstName;
24. }
25. public String getLastName() {
26. return lastName;
27. }
28. public void setLastName(String lastName) {
29. this.lastName = lastName;
30. }
31. }

 

 

 

 使用演示

 

Java代码  [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. package com.wisely.ij.service;
02. import com.wisely.ij.domain.Address;
03. import com.wisely.ij.domain.User;
04. import org.springframework.cache.annotation.Cacheable;
05. import org.springframework.stereotype.Service;
06. /\**
07. * Created by wisely on 2015/5/25.
08. \*/
09. @Service
10. public class DemoService {
11. @Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator")
12. public User findUser(Long id,String firstName,String lastName){
13. System.out.println("无缓存的时候调用这里");
14. return new User(id,firstName,lastName);
15. }
16. @Cacheable(value = "addresscache",keyGenerator = "wiselyKeyGenerator")
17. public Address findAddress(Long id,String province,String city){
18. System.out.println("无缓存的时候调用这里");
19. return new Address(id,province,city);
20. }
21. }

 

 

 

Java代码  [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. package com.wisely.ij.web;
02. import com.wisely.ij.domain.Address;
03. import com.wisely.ij.domain.User;
04. import com.wisely.ij.service.DemoService;
05. import org.springframework.beans.factory.annotation.Autowired;
06. import org.springframework.stereotype.Controller;
07. import org.springframework.web.bind.annotation.RequestMapping;
08. import org.springframework.web.bind.annotation.ResponseBody;
09. /\**
10. * Created by wisely on 2015/5/25.
11. \*/
12. @Controller
13. public class DemoController {
14. @Autowired
15. DemoService demoService;
16. @RequestMapping("/test")
17. @ResponseBody
18. public String putCache(){
19. demoService.findUser(1l,"wang","yunfei");
20. demoService.findAddress(1l,"anhui","hefei");
21. System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
22. return "ok";
23. }
24. @RequestMapping("/test2")
25. @ResponseBody
26. public String testCache(){
27. User user = demoService.findUser(1l,"wang","yunfei");
28. Address address =demoService.findAddress(1l,"anhui","hefei");
29. System.out.println("我这里没执行查询");
30. System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName());
31. System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity());
32. return "ok";
33. }
34. }

 

 

 

# 5 检验

 

 

 

先访问http://localhost:8080/test 保存缓存

 

![](http://dl2.iteye.com/upload/attachment/0108/8840/7a76af06-dc6b-33f2-b103-75cceb6040b7.jpg)  
 

 

再访问http://localhost:8080/test2 调用缓存里的数据

 

 

 

![](http://dl2.iteye.com/upload/attachment/0108/8842/c57ec989-970c-33e4-bca7-3908c42cace9.jpg)