spring-boot集成redis
application.properties
#redis 配置
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.102.128
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=6000
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=50
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=10
# 连接超时时间(毫秒)
spring.redis.timeout=6000
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.5.2.RELEASE</version>
</dependency> <dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>1.0.2</version>
</dependency>
RedisConfig.java
package com.hbd.example.framework.cache.redis; import org.springframework.beans.factory.annotation.Autowired;
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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig; import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map; @Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Autowired
private RedisConn redisConn; /**
* 生产key的策略
*
* @return
*/ @Bean
@Override
public KeyGenerator keyGenerator() {
System.err.println("================>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();
}
}; } /**
* 管理缓存
*
* @param redisTemplate
* @return
*/ @SuppressWarnings("rawtypes")
@Bean
public CacheManager CacheManager(RedisTemplate redisTemplate) {
System.err.println("================>CacheManager");
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 设置cache过期时间,时间单位是秒
rcm.setDefaultExpiration(60);
Map<String, Long> map = new HashMap<String, Long>();
map.put("test", 60L);
rcm.setExpires(map);
return rcm;
} /**
* redis 数据库连接池
* @return
*/
@Bean
public JedisPoolConfig redisPoolConfig() {
System.err.println("================>redisPoolConfig");
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(redisConn.getMaxActive());
poolConfig.setMaxIdle(redisConn.getMaxIdle());
poolConfig.setMinIdle(redisConn.getMinIdle());
poolConfig.setMaxWaitMillis(redisConn.getMaxWait());
return poolConfig;
} @Bean
public JedisConnectionFactory redisConnectionFactory() {
System.err.println("================>redisConnectionFactory");
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisConn.getHost());
factory.setPort(redisConn.getPort());
factory.setTimeout(redisConn.getTimeout()); // 设置连接超时时间
factory.setPoolConfig(redisPoolConfig());
return factory;
} /**
* redisTemplate配置
*
* @param factory
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
System.err.println("================>redisTemplate");
StringRedisSerializer keySerializer = new StringRedisSerializer();
JdkSerializationRedisSerializer valueSerializer = new JdkSerializationRedisSerializer();
StringRedisTemplate template = new StringRedisTemplate(factory);
template.setKeySerializer(keySerializer);
template.setValueSerializer(valueSerializer);
template.setConnectionFactory(redisConnectionFactory());
template.afterPropertiesSet();
return template;
} }
RedisConn.java
package com.hbd.example.framework.cache.redis; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConn {
private String host; private int port; private int timeout; @Value("${spring.redis.pool.max-active}")
private int maxActive; @Value("${spring.redis.pool.max-idle}")
private int maxIdle; @Value("${spring.redis.pool.min-idle}")
private int minIdle; @Value("${spring.redis.pool.max-wait}")
private int maxWait; public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public int getTimeout() {
return timeout;
} public void setTimeout(int timeout) {
this.timeout = timeout;
} public int getMaxActive() {
return maxActive;
} public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
} public int getMaxIdle() {
return maxIdle;
} public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
} public int getMinIdle() {
return minIdle;
} public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
} public int getMaxWait() {
return maxWait;
} public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
}
RedisUtil.java
package com.hbd.example.framework.cache.redis; import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component; import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit; /**
* redis cache 工具类
*
*/ @Component
public final class RedisUtil { @Resource
private RedisTemplate<Serializable, Object> redisTemplate; private String redisIp; /**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
} /**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
} /**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
} /**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
} /**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
// System.err.println("-----------------------------redisIp"+redisIp);
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
// System.err.println("-----------------------------redisIp" + redisIp);
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
// System.err.println("-----------------------------redisIp"+redisIp);
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
} public String getRedisIp() {
return redisIp;
} public void setRedisIp(String redisIp) {
this.redisIp = redisIp;
} /**
* 设置新值,同时返回旧值
* @param lockKey
* @param stringOfLockExpireTime
* @return
*/
public String getSet(final String lockKey, final String stringOfLockExpireTime) {
String result = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
byte[] bytes = redisConnection.getSet(lockKey.getBytes(), stringOfLockExpireTime.getBytes());
if(bytes != null) {
return new String(bytes);
}
return null;
}
});
return result;
} /**
* 如果不存在key则插入
* @param lockKey
* @param stringOfLockExpireTime
* @return true 插入成功, false 插入失败
*/
public boolean setnx(final String lockKey, final String stringOfLockExpireTime) {
return redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
return redisConnection.setNX(lockKey.getBytes(), stringOfLockExpireTime.getBytes());
}
});
} /**
* setnx 和 getSet方式插入的数据,调用此方法获取
* @param key
* @return
*/
public String getInExecute(final String key) {
String result = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
byte[] bytes = redisConnection.get(key.getBytes());
if (bytes == null) {
return null;
} else {
return new String(bytes);
}
}
});
return result;
} /**
* 将缓存保存在map集合中
* @param redisKey
* @param mapKey
* @param mapValue
* @return
*/
public boolean putInMap(final String redisKey, String mapKey, Object mapValue) {
boolean result = false;
try {
HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
operations.put(redisKey, mapKey, mapValue);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public Object getOneFromMap(final String redisKey, String mapKey) {
HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
return operations.get(redisKey, mapKey);
} public Object getAllFromMap(final String redisKey) {
HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
return operations.values(redisKey);
} public void removeFromMap(final String redisKey, Object obj) {
HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
operations.delete(redisKey, obj);
} public boolean setList(final String key, Object value) {
boolean result = false;
try {
ListOperations<Serializable, Object> listOperations = redisTemplate.opsForList();
listOperations.leftPush(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public Object getList(final String key) {
ListOperations<Serializable, Object> listOperations = redisTemplate.opsForList();
return listOperations.range(key,0,listOperations.size(key));
} }
OrgController.java
package com.hbd.example.org.controller; import com.hbd.example.framework.cache.redis.RedisUtil;
import com.hbd.example.framework.exception.runtime.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController
@RequestMapping("/org")
public class OrgController { @Resource
RedisUtil redisUtil; @RequestMapping("/set")
public String set(@RequestParam String key, @RequestParam String value) {
redisUtil.set(key,value);
return "success";
} @RequestMapping("/get")
public String get(String key) {
Object o = redisUtil.get(key);
System.out.println(o);
return "redis value :"+o;
} }
spring-boot集成redis的更多相关文章
- (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
[本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...
- Spring Boot 2.X(六):Spring Boot 集成Redis
Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...
- SpringBoot(十一): Spring Boot集成Redis
1.在 pom.xml 中配置相关的 jar 依赖: <!-- 加载 spring boot redis 包 --> <dependency> <groupId>o ...
- spring boot集成redis基础入门
redis 支持持久化数据,不仅支持key-value类型的数据,还拥有list,set,zset,hash等数据结构的存储. 可以进行master-slave模式的数据备份 更多redis相关文档请 ...
- 【spring boot】【redis】spring boot 集成redis的发布订阅机制
一.简单介绍 1.redis的发布订阅功能,很简单. 消息发布者和消息订阅者互相不认得,也不关心对方有谁. 消息发布者,将消息发送给频道(channel). 然后是由 频道(channel)将消息发送 ...
- spring boot集成redis实现session共享
1.pom文件依赖 <!--spring boot 与redis应用基本环境配置 --> <dependency> <groupId>org.springframe ...
- spring boot 集成 redis lettuce
一.简介 spring boot框架中已经集成了redis,在1.x.x的版本时默认使用的jedis客户端,现在是2.x.x版本默认使用的lettuce客户端,两种客户端的区别如下 # Jedis和L ...
- Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
转自:https://blog.csdn.net/linxingliang/article/details/52263763 spring boot 自学笔记(三) Redis集成—RedisTemp ...
- spring boot 集成 redis lettuce(jedis)
spring boot框架中已经集成了redis,在1.x.x的版本时默认使用的jedis客户端,现在是2.x.x版本默认使用的lettuce客户端 引入依赖 <!-- spring boot ...
- Spring Boot集成Redis集群(Cluster模式)
目录 集成jedis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 集成spring-data-redis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 异常处理 同样的, ...
随机推荐
- 关于ARM中的tst、cmp、bne、beq指令
一.关于cmp的详细用法 假设现在AX寄存器中的数是0002H,BX寄存器中的数是0003H. 执行的指令是:CMP AX, BX 执行这条指令时,先做用AX中的数减去BX中的数的减法运算. 列出二进 ...
- bootstrap -- css -- 按钮
本文中提到的按钮样式,适用于:<a>, <button>, 或 <input> 元素上 但最好在 <button> 元素上使用按钮 class,避免跨浏 ...
- opengl wglsharelists
原文地址:http://blog.csdn.net/webscaler/article/details/5873179 OpenGL 中用到多线程和多 render context 渲染的时候会用到 ...
- 学习 TList 类的实现[5]
先来实现 TMyList.SetCapacity. 马上会想到下面代码: procedure TMyList.SetCapacity(const Value: Integer); begin if ...
- Ubuntu:为 Firefox 浏览器 安装 flash 插件
从adobe上下载浏览器flashplayer插件:推荐 x.tar.gz格式的——通用格式. 解压tar.gz后可以得到:libflashplayer.so 文件 将 libflashplayer. ...
- 为什么MathType窗口变灰色
mathtype是一个功能强大的数学公式编辑器,可以轻松输入各种复杂的公式和符号,与Office文档完美结合,显示效果超好,比Office自带的公式编辑器要强大很多.但我们在使用MathType编辑公 ...
- java 正则表达式验证
package com.fsti.icop.util.regexp; import java.util.regex.Matcher; import java.util.regex.Pattern; p ...
- [redis] redis 对string类型数据操作
package com.xwolf.java.redis; import org.junit.Before; import org.junit.Test; import redis.clients.j ...
- DUBBO功能使用说明
DUBBO功能使用说明 1 DUBBO概述 DUBBO是阿里巴巴公司的一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案. 相比于其他服务框架,DUBBO有如 ...
- oracle 存储过程 where in参数传入问题
问题: 举个简单例子说明create or replace procedure procStr(inString in varchar2)asbeginselect * from book where ...