项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821

pom.xml添加对redis的依赖:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>

application.yml配置redis启动参数:

spring:
redis:
# Redis服务器地址
host: localhost
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池中的最大空闲连接
min-idle: 0
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最小空闲连接
max-idle: 8
# 连接超时时间(毫秒)
timeout: 20

Redis的启动类如下:

package com.sun.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.boot.bind.RelaxedPropertyResolver;
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.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
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 redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method; /**
* 项目启动加载redis
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport implements EnvironmentAware { private final Logger logger = Logger.getLogger(RedisConfig.class); private RelaxedPropertyResolver propertyResolver; public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env, "spring.redis.");
} @Bean("jedisPool")
public JedisPool redisPoolFactory() {
logger.info("redis地址:" + propertyResolver.getProperty("host") +
":" + propertyResolver.getProperty("port"));
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(Integer.valueOf(propertyResolver.getProperty("pool.max-idle")));
jedisPoolConfig.setMaxWaitMillis(Integer.valueOf(propertyResolver.getProperty("pool.max-wait"))); JedisPool jedisPool = new JedisPool(jedisPoolConfig, propertyResolver.getProperty("host"),
Integer.valueOf(propertyResolver.getProperty("port")),
Integer.valueOf(propertyResolver.getProperty("timeout")));
logger.info("jedisPool注入成功!!");
return jedisPool;
}
/**
* 生成key的策略
* 缓存注解没有配置key参数走此方法
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
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();
}
};
}
/**
* RedisTemplate配置
* @param factory
* @return
*/
@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;
}
/**
* 管理缓存
*
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间--一天
rcm.setDefaultExpiration(86400);//秒
return rcm;
} }

在ServiceImpl业务处理类上使用注解:

@Cacheable(value="common",key="'id_'+#id")
public User selectByPrimaryKey(Integer id) {
return userMapper.selectByPrimaryKey(id);
}

前台输入地址调用后台可以看到第一个打印出执行的sql,第二次不打印

项目启动前需要启动redis服务器,不知道的可以参考博客:http://blog.csdn.net/aqsunkai/article/details/51324176

SpringBoot学习:整合Redis的更多相关文章

  1. SpringBoot简单整合redis

    Jedis和Lettuce Lettuce 和 Jedis 的定位都是Redis的client,所以他们当然可以直接连接redis server. Jedis在实现上是直接连接的redis serve ...

  2. SpringBoot学习(七)—— springboot快速整合Redis

    目录 Redis缓存 简介 引入redis缓存 代码实战 Redis缓存 @ 简介 redis是一个高性能的key-value数据库 优势 性能强,适合高度的读写操作(读的速度是110000次/s,写 ...

  3. SpringBoot之整合Redis分析和实现-基于Spring Boot2.0.2版本

    背景介绍 公司最近的新项目在进行技术框架升级,基于的Spring Boot的版本是2.0.2,整合Redis数据库.网上基于2.X版本的整个Redis少之又少,中间踩了不少坑,特此把整合过程记录,以供 ...

  4. springBoot(8)---整合redis

    Springboot整合redis 步骤讲解 1.第一步jar导入: <dependency> <groupId>org.springframework.boot</gr ...

  5. 【SpringBoot】整合Redis实战

    ========================9.SpringBoot2.x整合Redis实战 ================================ 1.分布式缓存Redis介绍 简介: ...

  6. 完整SpringBoot Cache整合redis缓存(二)

    缓存注解概念 名称 解释 Cache 缓存接口,定义缓存操作.实现有:RedisCache.EhCacheCache.ConcurrentMapCache等 CacheManager 缓存管理器,管理 ...

  7. SpringBoot中整合Redis、Ehcache使用配置切换 并且整合到Shiro中

    在SpringBoot中Shiro缓存使用Redis.Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这sh ...

  8. SpringBoot之整合Redis

    一.SpringBoot整合单机版Redis 1.在pom.xml文件中加入redis的依赖 <dependency> <groupId>org.springframework ...

  9. springboot下整合redis使用redisTemplate模板

    pom <!-- 引入 redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupI ...

  10. springboot+JPA 整合redis

    1.导入redis依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifact ...

随机推荐

  1. 函数类型(Function Types):函数类型和其他类型一样

    函数类型(Function Types) 每个函数都有种特定的函数类型,由函数的参数类型和返回类型组成. 例如: 这个例子中定义了两个简单的数学函数:addTwoInts 和 multiplyTwoI ...

  2. 谁把我的表给drop了?

    今天生产上有人把几张表给DROP了,一通折腾.恢复备份导数回来数据,重建索引. 但是,我就想知道是谁给干掉了. 到你被删除表数据库中找日志吧.其它的也想不到更好办法了 USE '被删表数据库' --查 ...

  3. PHP中__get()和__set()的用法实例详

    刚刚看到一个对我有用的文章,我就把它摘抄下来了.                                                                        php面 ...

  4. [转]C# 指针之美

     将C#图像库的基础部分开源了(https://github.com/xiaotie/GebImage).这个库比较简单,且离成熟还有一段距离,但它是一种新的开发模式的探索:以指针和非托管内存为主的C ...

  5. iis服务器php环境 failed to open stream: No such file or directory解决办法

    项目主机用的windows系统,iis服务器:远程连接桌面—>本地资源->映射D盘驱动器,将本地d盘修改后的文件放在远程主机项目目录里,访问报出failed to open stream: ...

  6. Oracle恢复误删数据

    1.先查出被删除的时间点: select * from flashback_transaction_query where table_name='表名'; 2.根据时间点恢复数据: insert i ...

  7. Oracle数据库,简单SQL练习与答案

    1.数据 --创建职员表create table tbEmp( eID number primary key, --职员编号 eName varchar2(20) not null, --职员姓名 e ...

  8. iOS之NSDictionary初始化的坑

    最近在做项目的时候遇到一个挺坑的崩溃问题,是由于NSDictionary初始化时nil指针引起的崩溃.假设我们现在要初始化一个{key1 : value1, key2 : value2, key3 : ...

  9. HTML基础之常用标签

    Meta 标签介绍 Meta的属性有两种:name和http-equiv name属性用于描述网页,对应于content <meta name="Generator" con ...

  10. 使用js函数格式化xml字符串带缩进

    遇到了一个做soap的API的操作,中途需要说明xml的组装模式等, 如上图,组装产生的mxl代码药格式化并展示.由于是在前端做的,所以需要将字符串将xml进行格式化并输出,找到别人写的算法稍加更改并 ...