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客户端 使用 验证 异常处理 同样的, ...
随机推荐
- 如何退出Activity?如何安全退出已调用多个Activity的Application?
对于单一Activity的应用来说,退出很简单,直接finish()即可. 1.抛异常强制退出: 该方法通过抛异常,使程序ForceClose. 验证可以,但是,需要解决的问题是,如何使程序结束掉,而 ...
- 【F12】修改 DevTools的主题
1.点击setting
- 【转】WCF入门教程四[WCF的配置文件]
一.概述 配置也是WCF编程中的主要组成部分.在以往的.net应用程序中,我们会把DBConn和一些动态加载类及变量写在配置文件里.但WCF有所不同.他指定向客户端公开的服务,包括服务的地址.服务用于 ...
- am335x hid-multitouch.c
am335x在使用电容屏,需要加载hid-multitouch.ko模块 由下面文件生成 kernel/drivers/hid/hid-multitouch.c 内核中编译模块 make module ...
- Oracle-05-SQL语句概述、分类&SQL*PLUS概述(初识insert,desc,list,r,del,a,c,n等命令)
一.SQL语句概述 (1)SQL全程是"结构化查询语言(Structured Query Language)". SQL是大多数主流数据库系统採用的标准查询语言. (2)SQL语句 ...
- iOS推送证书从申请到使用
关于这个话题,已经有非常多写的非常好的文章了.可是,在自己做的过程中,即使别人写的已经非常好了,还是会遇到这样那样的问题. 自己还是再写一遍吧. 本文记录了从无到有申请证书,到最后可以发出通知.当然, ...
- php纯原生实现数组二分法
代码如下 $arr = [1,3,5,7,9];//$arr = range(1,10000);var_dump(find($arr, 2)); function find(array $arr, $ ...
- mongoDB的shell数组操作器
http://www.2cto.com/database/201304/205024.html mongoDB数组操作器 $push会向数组末尾加入一个元素,如果数组不存在,则会创建这个数组. 增 ...
- Java精选笔记_会话技术
会话及其会话技术 会话概述 指的是一个客户端(浏览器)与Web服务器之间连续发生的一系列请求和响应过程. 会话:从浏览器开启到浏览器关闭.会话技术:用来保存在会话期间 浏览器和服务器所产生的数据. 在 ...
- python 数据类型详解(转)
转自:http://www.cnblogs.com/linjiqin/p/3608541.html 目录1.字符串2.布尔类型3.整数4.浮点数5.数字6.列表7.元组8.字典9.日期 1.字符串1. ...