Spring Boot 1.2.5使用redis做数据缓存
2016-06-30 10:30
786 查看
1 添加redis支持
在pom.xml中添加Xml代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
[xml]
view plain
copy
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
2 redis配置
Java代码package com.wisely.ij.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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 java.lang.reflect.Method;
@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(
@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
@Bean
public RedisTemplate<String, String> redisTemplate(
RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
[java]
view plain
copy
package com.wisely.ij.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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 java.lang.reflect.Method;
@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(
@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
@Bean
public RedisTemplate<String, String> redisTemplate(
RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
3 redis服务器配置
Properties代码# REDIS (RedisProperties)
spring.redis.database= # database name
spring.redis.host=localhost # server host
spring.redis.password= # server password
spring.redis.port=6379 # connection port
spring.redis.pool.max-idle=8 # pool settings ...
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.sentinel.master= # name of Redis server
spring.redis.sentinel.nodes= # comma-separated list of host:port pairs
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]
view plain
copy
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]
view plain
copy
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;
/**
* Created by wisely on 2015/5/25.
*/
@Service
public class DemoService {
@Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator")
public User findUser(Long id,String firstName,String lastName){
System.out.println("无缓存的时候调用这里");
return new User(id,firstName,lastName);
}
@Cacheable(value = "addresscache",keyGenerator = "wiselyKeyGenerator")
public Address findAddress(Long id,String province,String city){
System.out.println("无缓存的时候调用这里");
return new Address(id,province,city);
}
}
[java]
view plain
copy
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;
/**
* Created by wisely on 2015/5/25.
*/
@Service
public class DemoService {
@Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator")
public User findUser(Long id,String firstName,String lastName){
System.out.println("无缓存的时候调用这里");
return new User(id,firstName,lastName);
}
@Cacheable(value = "addresscache",keyGenerator = "wiselyKeyGenerator")
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;
/**
* Created by wisely on 2015/5/25.
*/
@Controller
public class DemoController {
@Autowired
DemoService demoService;
@RequestMapping("/test")
@ResponseBody
public String putCache(){
demoService.findUser(1l,"wang","yunfei");
demoService.findAddress(1l,"anhui","hefei");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return "ok";
}
@RequestMapping("/test2")
@ResponseBody
public String testCache(){
User user = demoService.findUser(1l,"wang","yunfei");
Address address =demoService.findAddress(1l,"anhui","hefei");
System.out.println("我这里没执行查询");
System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName());
System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity());
return "ok";
}
}
[java]
view plain
copy
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;
/**
* Created by wisely on 2015/5/25.
*/
@Controller
public class DemoController {
@Autowired
DemoService demoService;
@RequestMapping("/test")
@ResponseBody
public String putCache(){
demoService.findUser(1l,"wang","yunfei");
demoService.findAddress(1l,"anhui","hefei");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return "ok";
}
@RequestMapping("/test2")
@ResponseBody
public String testCache(){
User user = demoService.findUser(1l,"wang","yunfei");
Address address =demoService.findAddress(1l,"anhui","hefei");
System.out.println("我这里没执行查询");
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 调用缓存里的数据; 更多详细了解:https://niyao88.taobao.com/
相关文章推荐
- redis mybatis spring整合
- Redis 教程
- 【Redis基础】Redis在项目中实战
- Spring+ehcache+redis两级缓存--缓存实战篇(1)
- Num63 前台用户注册&redis的简单java使用
- redis学习笔记
- scrapy-redis分布式爬虫原理分析
- redis在spring框架中的使用
- Redis_hase常用命令
- Windows下Redis的安装及PHP扩展使用
- 【Mark】redis入门教程
- redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resourc
- PHP使用php-resque库配合Redis实现MQ消息队列的教程
- Redis的三种启动方式
- linux安装redis官方教程
- Redis监控方案
- Node.js操作redis示例及常用命令汇总
- redis主从复制
- centos7安装redis3.2.1
- redis 用setbit(bitmap)统计活跃用户