Spring Boot使用redis做数据缓存
2016-04-26 19:33
906 查看
1 添加redis支持
在pom.xml中添加Xml代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
2 redis配置
Java代码 package com.wisely.ij.config;
import java.lang.reflect.Method;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Bean
public KeyGenerator wiselyKeyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
@Bean
public RedisTemplate<String, String> redisTemplate(
RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
om.enableDefaultTyping(DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
3 redis服务器配置
Properties代码 # REDIS (RedisProperties)
spring.redis.database=0 # database name
spring.redis.host=localhost # server host
spring.redis.password= # server password
spring.redis.port=6379 # connection port
spring.redis.pool.max-idle=10 # pool settings ...
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=10
spring.redis.pool.max-wait=-1
4 应用
测试两个实体类Java代码
package com.wisely.ij.domain;
public class Address {
private Long id;
private String province;
private String city;
public Address(Long id,String province, String city) {
this.id = id;
this.province = province;
this.city = city;
}
public Address() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Java代码
package com.wisely.ij.domain;
public class User {
private Long id;
private String firstName;
private String lastName;
public User(Long id,String firstName, String lastName) {
this.id = id ;
this.firstName = firstName;
this.lastName = lastName;
}
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
使用演示
Java代码
package com.wisely.ij.service;
import com.wisely.ij.domain.Address;
import com.wisely.ij.domain.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Cacheable(value = "usercache", key = "#id + '_' + #firstName + '_' + #lastName")
public User findUser(Long id,String firstName,String lastName){
System.out.println("无缓存的时候调用这里。");
return new User(id,firstName,lastName);
}
@Cacheable(value = "addresscache", key = "#id + '_' + #province + '_' + #city")
public Address findAddress(Long id,String province,String city){
System.out.println("无缓存的时候调用这里。");
return new Address(id,province,city);
}
}
Java代码
package com.wisely.ij.web;
import com.wisely.ij.domain.Address;
import com.wisely.ij.domain.User;
import com.wisely.ij.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@RestController
public class DemoEndpoint{
@Autowired
DemoService demoService;
@RequestMapping(value = "/test", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String putCache(){
demoService.findUser(1L, "zhang", "san");
demoService.findAddress(2L, "jx", "gz");
System.out.println("if it not print '无缓存的时候调用。' ,it means the test is success.");
return "OK";
}
@RequestMapping(value = "/test2", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String testCache(){
User user = demoService.findUser(1L, "zhang", "san");
Address address =demoService.findAddress(2L, "jx", "gz");
System.out.println("it not excute query");
System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName());
System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity());
return "OK";
}
}
5 检验
先访问http://localhost:8080/test 保存缓存
再访问http://localhost:8080/test2 调用缓存里的数据
相关文章推荐
- redis安装问题小结
- 使用 Redis 和 Python 构建一个共享单车的应用程序
- Redis偶发连接失败案例实战记录
- Redis中实现查找某个值的范围
- redis的hGetAll函数的性能问题(记Redis那坑人的HGETALL)
- Redis和Memcached的区别详解
- 分割超大Redis数据库例子
- Redis总结笔记(一):安装和常用命令
- Redis sort 排序命令详解
- 用Redis实现微博关注关系
- Redis实现信息已读未读状态提示
- redis中修改配置文件中的端口号 密码方法
- 在Ruby on Rails上使用Redis Store的方法
- 浅析SQL Server中的执行计划缓存(上)
- Enterprise Library for .NET Framework 2.0缓存使用实例
- Redis和Memcache的区别总结
- PowerShell中编程清空IE缓存方法
- PowerShell中使用.NET将程序集加入全局程序集缓存
- C#中缓存的基本用法总结
- 在Node.js应用中使用Redis的方法简介