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的更多相关文章

  1. (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...

  2. Spring Boot 2.X(六):Spring Boot 集成Redis

    Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...

  3. SpringBoot(十一): Spring Boot集成Redis

    1.在 pom.xml 中配置相关的 jar 依赖: <!-- 加载 spring boot redis 包 --> <dependency> <groupId>o ...

  4. spring boot集成redis基础入门

    redis 支持持久化数据,不仅支持key-value类型的数据,还拥有list,set,zset,hash等数据结构的存储. 可以进行master-slave模式的数据备份 更多redis相关文档请 ...

  5. 【spring boot】【redis】spring boot 集成redis的发布订阅机制

    一.简单介绍 1.redis的发布订阅功能,很简单. 消息发布者和消息订阅者互相不认得,也不关心对方有谁. 消息发布者,将消息发送给频道(channel). 然后是由 频道(channel)将消息发送 ...

  6. spring boot集成redis实现session共享

    1.pom文件依赖 <!--spring boot 与redis应用基本环境配置 --> <dependency> <groupId>org.springframe ...

  7. spring boot 集成 redis lettuce

    一.简介 spring boot框架中已经集成了redis,在1.x.x的版本时默认使用的jedis客户端,现在是2.x.x版本默认使用的lettuce客户端,两种客户端的区别如下 # Jedis和L ...

  8. Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    转自:https://blog.csdn.net/linxingliang/article/details/52263763 spring boot 自学笔记(三) Redis集成—RedisTemp ...

  9. spring boot 集成 redis lettuce(jedis)

    spring boot框架中已经集成了redis,在1.x.x的版本时默认使用的jedis客户端,现在是2.x.x版本默认使用的lettuce客户端 引入依赖 <!-- spring boot ...

  10. Spring Boot集成Redis集群(Cluster模式)

    目录 集成jedis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 集成spring-data-redis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 异常处理 同样的, ...

随机推荐

  1. Qt中的串口编程之一

    QtSerialPort 简介 功能介绍 SerialPort SerialPortInfo 源代码 编译和安装 配置编译环境 Perl只是在Qt5的时候才需要Qt4的情况下可以不配置 使用如下推荐步 ...

  2. 弄明白html、css3、js这个问题。。。

  3. 关于Cocos2d-x数据类型的使用

    常用的是三种数据类型,Value,Vector,Map,翻译成中文就是值,数组,字典.其中字典的意思就是拿着某个关键字去这个数据结构里面找相应的对应的数据. //Value数据类型 Value int ...

  4. struts2中struts.xml和web.xml文件解析及工作原理

    web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp ...

  5. Mac OS Yosemite 文件批量重命名

    首先,我们选中一个文件夹   右键,或者回车,给一个文件夹改名   同时选中三个文件夹   右键,选中批量更改   弹出批量更改,进行更改   改好后点回车,就能看到效果了   继续操作,完成所有文件 ...

  6. BinarySearchTree二叉搜索树的实现

    /* 二叉搜索树(Binary Search Tree),(又:二叉查找树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; ...

  7. 10种canvas鼠标光标动画特效

    来源:http://www.sucaihuo.com/js/1780.html demo:http://www.sucaihuo.com/jquery/17/1780/demo/

  8. 第六章 mybatis注入映射器

    为了代替手工使用 SqlSessionDaoSupport 或 SqlSessionTemplate 编写数据访问对象 (DAO)的代码,MyBatis-Spring 提供了一个动态代理的实现:Map ...

  9. 有限状态机FSM详解及其实现

    有限状态机,也称为FSM(Finite State Machine),其在任意时刻都处于有限状态集合中的某一状态.当其获得一个输入字符时,将从当前状态转换到另一个状态,或者仍然保持在当前状态.任何一个 ...

  10. Faster-RCNN