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客户端 使用 验证 异常处理 同样的, ...
随机推荐
- java中Scanner的nextLine()和next()的区别
首先,next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键.Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后 ...
- 控件activeX开发之项目ffmpeg解码h264——总结
1. 编译好ffmpeg的lib库和dll库 2. 播放器作为一个dilog类player,然后在ctrol中的oncreate重写方法中用全局属性cplayer *player里new cplaye ...
- 初识Comet技术
一.服务器推送技术概述 服务器推送技术(Servers Push)的基础思想是将浏览器主动查询信息改为服务器主动发送信息.服务器发送一批数据,浏览器显示这些数据,同时保证与服务器的连接.当服务器需要再 ...
- bootstrap -- meta中的viewport指令
在查看bootstrap教程中,碰到 <meta name="viewport" content="width=device-width, initial-scal ...
- atitit.javascript调用java in swt attilax 总结
atitit.javascript调用java in swt attilax 总结 1. BrowserFunction 简单介绍1 1.1. BrowserFunction 能够分为三类: 1 1. ...
- 未能在当前目标框架中解析主引用“System.Net.Http”,它是一个框架程序集。“.NETFramework,Version=v4.0”。若要解决此问题,请移除引用“System.Net.Http”,或将应用程序的目标重新指向包含“System.Net.Http”的框架版本。 Zephyr.Web
解决方法:升级项目到.net framework 4.5
- jquery widgets 弹框
<div id='dialog' style="display:none;"> <div style="text-align:center;" ...
- Linux内核剖析 之 内存管理
1. 内存管理区 为什么分成不同的内存管理区? ISA总线的DMA处理器有严格的限制:仅仅能对物理内存前16M寻址. 内核线性地址空间仅仅有1G,CPU不能直接訪问全部的物理内存. ZONE_DMA ...
- [转] 在图标库中,找到合适的图标 ico
作者:xlrocket链接:https://www.zhihu.com/question/19857245/answer/241696797 在图标库中,找到合适的图标 或许,一些小伙伴会有收集图标的 ...
- linux下 redis 启动
启动文件 startredis.sh : nohup /data/redis/bin/redis-server /data/redis/etc/redis.conf & 关闭文件 stopr ...