SpringCloud中Redis的使用
1.引入redis相关jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency> <dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>1.0.2</version>
</dependency>
pom 配置
2.配置Redis相关信息
#redis 配置
# Redis数据库索引(默认为0)
spring.redis.database=${dev.spring.redis.database}
# Redis服务器地址
spring.redis.host=${dev.spring.redis.host}
# Redis服务器连接端口
spring.redis.port=${dev.spring.redis.port}
# Redis服务器连接密码(默认为空)
spring.redis.password=${dev.spring.redis.password}
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=${dev.spring.redis.pool.max-active}
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=${dev.spring.redis.pool.max-wait}
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=${dev.spring.redis.pool.max-idle}
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=${dev.spring.redis.pool.min-idle}
# 连接超时时间(毫秒)
spring.redis.timeout=${dev.spring.redis.timeout}
config.properties
3.读取Redis链接信息 RedisConn
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConn {
private String host;
//prefix+参数名 对应于配置文件config.properties中的spring.redis.*信息
private int port; private int timeout;
redis 链接pojo
4.RedisConfig
package com.sinosoft.product.service.redis; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer; 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() {
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) {
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 JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisConn.getHost());
factory.setPort(redisConn.getPort());
factory.setTimeout(redisConn.getTimeout()); // 设置连接超时时间
return factory;
} /**
* redisTemplate配置
*
* @param factory
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@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;
} }
RedisConfig
5.RedisUtils Redis工具类
package com.sinosoft.product.service.redis; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component; import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit; @Component
public class RedisUtil{
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate; /**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
} /**
* 批量删除key
*
* @param pattern
*/
@SuppressWarnings("unchecked")
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
} /**
* 删除对应的value
*
* @param key
*/
@SuppressWarnings("unchecked")
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
} /**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
} /**
* 读取缓存
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value) {
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
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value, Long expireTime) {
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;
} }
RedisUtil
6.Redis的使用
//注入Redis的工具类 @Autowired
private RedisUtils redisUtil; //判断Redis中是否存在对应key的信息,若存在则在reids中获取,若不存在从数据库查询,同时存入redis缓存中 if (redisUtil.exists(calcode+calFlag)) {
Log.info("从Redis缓存中获取产品计算编码:{" + calcode+calFlag + "}信息");
tLMCalCulate = (LMCalCulate) redisUtil.get(calcode+calFlag);
} else {
LMCalCulateExample tLMCalCulateExample=new LMCalCulateExample();
tLMCalCulateExample.createCriteria().andCalcodeEqualTo(calcode).andCalflgEqualTo(calFlag);
List<LMCalCulate> tListLMCalCulate = lMCalCulateMapper.selectByExample(tLMCalCulateExample);
if(null!=tListLMCalCulate && tListLMCalCulate.size()>0){
tLMCalCulate=tListLMCalCulate.get(0);
redisUtil.set(calcode+calFlag, tLMCalCulate);
}
}
redis应用
SpringCloud中Redis的使用的更多相关文章
- SpringCloud+MyBatis+Redis整合—— 超详细实例(二)
2.SpringCloud+MyBatis+Redis redis①是一种nosql数据库,以键值对<key,value>的形式存储数据,其速度相比于MySQL之类的数据库,相当于内存读写 ...
- Springcloud 中 SpringBoot 配置全集 (收藏版)
Springcloud 中 SpringBoot 配置全集 (收藏版) 疯狂创客圈 Java 高并发[ 亿级流量聊天室实战]实战系列 [博客园总入口 ] 前言 疯狂创客圈(笔者尼恩创建的高并发研习社群 ...
- Laravel 5.1中 Redis 的安装配置及基本使用教程
关于Redis的介绍我们在之前Laravel 缓存配置一节中已有提及,Redis是一个开源的.基于内存的数据结构存储器,可以被用作数据库.缓存和消息代理.相较Memcached而言,支持更加丰富的数据 ...
- Linux中redis安装配置及使用详解
Linux中redis安装配置及使用详解 一. Redis基本知识 1.Redis 的数据类型 字符串 , 列表 (lists) , 集合 (sets) , 有序集合 (sorts sets) , 哈 ...
- go中redis使用小结
最近做了个关于redis的项目,那么就整理下遇到和未遇到的问题 1.redis的简介安装 2.redis的数据结构 3.Redis基本使用 4.Redis的并发 5.Redis的落地 一.redis的 ...
- SpringCloud中eureka配置心跳和剔除下线的服务的时间
在默认的springCloud中eureka注册中心在服务下线时表现的非常不灵敏,用惯了dubbo的zk注册中心表示很不习惯,eureka设计的本意是在服务不会频繁上下线和网络稳定的内网,这种设计在生 ...
- SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍
今天给大家介绍一下SpringBoot中Redis的set.map.list.value等基本操作的具体使用方法 上一节中给大家介绍了如何在SpringBoot中搭建Redis缓存数据库,这一节就针对 ...
- SpringBoot(三) :Spring boot 中 Redis 的使用
前言: 这一篇讲的是Spring Boot中Redis的运用,之前没有在项目中用过Redis,所以没有太大的感觉,以后可能需要回头再来仔细看看. 原文出处: 纯洁的微笑 SpringBoot对常用的数 ...
- Django中redis的使用方法(包括安装、配置、启动)
一.安装redis: 1.下载: wget http://download.redis.io/releases/redis-3.2.8.tar.gz 2.解压 tar -zxvf redis-3.2. ...
随机推荐
- Taro:使用taro完成小程序开发
前言:taro是一个可以很好实现一次开发,多端统一的框架,本文只介绍它小程序端开发的一些内容.小程序项目搭建gitup已经有很清楚的说明:https://github.com/NervJS/taro ...
- LeetCode(95) Unique Binary Search Trees II
题目 Given n, generate all structurally unique BST's (binary search trees) that store values 1-n. For ...
- PAT Basic 1022
1022 D进制的A+B 输入两个非负10进制整数A和B(<=2^30^-1),输出A+B的D (1 < D <= 10)进制数. 输入格式: 输入在一行中依次给出3个整数A.B和D ...
- Struts2之初体验
Struts21.了解Struts2 请求调度框架Struts2是一个MVC框架Struts2类库:Struts2-core Struts2核心XWork-core xwork核心 Struts2的构 ...
- 关于php使用xpath解析html中文乱码问题
$str2 = '<div id="content">我很好 </div>'; $dom = new DOMDocument(); //load之前强转字符 ...
- Java POI 操作Excel(读取/写入)
pom.xml依赖: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi< ...
- python基础学习笔记——生成器与推导式
生成器 首先我们来看看什么是个生成器,生成器本质就是迭代器 在python中有三种方式来获取生成器 1.通过生成器函数 2.通过各种推到式来实现生成器 3.通过数据的转换也可以获取生成器 首先,我们先 ...
- eval() 函数 解析json对象
eval在js中用来运行以js源码组成的字符串. 可以用来改变全局或者局部变量,例如: var globalEval = eval; //定义全局eval函数别名 var a ='global', b ...
- 请编写一个方法,返回某集合的所有非空子集。 给定一个int数组A和数组的大小int n,请返回A的所有非空子集。保证A的元素个数小于等于20,且元素互异。各子集内部从大到小排序,子集之间字典逆序排序,见样例。
题解:观察测试样例,会发现每个子集的选择规律与二进制((2^n) - 1)到 1 的顺序生成的规律是一致的,样例中n=3,2^n-1=7,用二进制表示为111,其中每一位的1表示数组中的三个数都选择. ...
- python3--__repr_和__str__会返回字符串表达形式
__repr_和__str__会返回字符串表达形式 下一个例子是已经见过的init构造方法和add重载方法,本例也会定义返回实例的字符串表达形式的__repr__方法.字符串格式把self.data对 ...