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

  1. SpringCloud+MyBatis+Redis整合—— 超详细实例(二)

    2.SpringCloud+MyBatis+Redis redis①是一种nosql数据库,以键值对<key,value>的形式存储数据,其速度相比于MySQL之类的数据库,相当于内存读写 ...

  2. Springcloud 中 SpringBoot 配置全集 (收藏版)

    Springcloud 中 SpringBoot 配置全集 (收藏版) 疯狂创客圈 Java 高并发[ 亿级流量聊天室实战]实战系列 [博客园总入口 ] 前言 疯狂创客圈(笔者尼恩创建的高并发研习社群 ...

  3. Laravel 5.1中 Redis 的安装配置及基本使用教程

    关于Redis的介绍我们在之前Laravel 缓存配置一节中已有提及,Redis是一个开源的.基于内存的数据结构存储器,可以被用作数据库.缓存和消息代理.相较Memcached而言,支持更加丰富的数据 ...

  4. Linux中redis安装配置及使用详解

    Linux中redis安装配置及使用详解 一. Redis基本知识 1.Redis 的数据类型 字符串 , 列表 (lists) , 集合 (sets) , 有序集合 (sorts sets) , 哈 ...

  5. go中redis使用小结

    最近做了个关于redis的项目,那么就整理下遇到和未遇到的问题 1.redis的简介安装 2.redis的数据结构 3.Redis基本使用 4.Redis的并发 5.Redis的落地 一.redis的 ...

  6. SpringCloud中eureka配置心跳和剔除下线的服务的时间

    在默认的springCloud中eureka注册中心在服务下线时表现的非常不灵敏,用惯了dubbo的zk注册中心表示很不习惯,eureka设计的本意是在服务不会频繁上下线和网络稳定的内网,这种设计在生 ...

  7. SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍

    今天给大家介绍一下SpringBoot中Redis的set.map.list.value等基本操作的具体使用方法 上一节中给大家介绍了如何在SpringBoot中搭建Redis缓存数据库,这一节就针对 ...

  8. SpringBoot(三) :Spring boot 中 Redis 的使用

    前言: 这一篇讲的是Spring Boot中Redis的运用,之前没有在项目中用过Redis,所以没有太大的感觉,以后可能需要回头再来仔细看看. 原文出处: 纯洁的微笑 SpringBoot对常用的数 ...

  9. Django中redis的使用方法(包括安装、配置、启动)

    一.安装redis: 1.下载: wget http://download.redis.io/releases/redis-3.2.8.tar.gz 2.解压 tar -zxvf redis-3.2. ...

随机推荐

  1. html2canvas.js网页截图功能

    需求:将网页生成图片,用户自行长按图片进行保存图片,再分享朋友圈.其中,都可识别图中的二维码.(二维码过小会识别不出) 首先,先来科普一下微信网页识别二维码原理:截屏识别,当客户端发现用户在网页的im ...

  2. 条款37:绝不重新定义继承而来的缺省参数值(Never redefine a function's inherited default parameter value)

    NOTE: 1.绝不重新定义一个继承而来的缺省参数值,因为缺省参数值都是静态绑定的,而virtual 函数-----你唯一应该覆盖的东西----却是动态绑定的.

  3. XML,面向对象基础

    什么是XML XML与JSON的对比 XML文档格式 使用XML模块解析 一,什么是XML ''' XML 全称可扩展标记语言 <tag></tag> 双标签 <tag/ ...

  4. Django2.0+小程序技术打造微信小程序助手百度云

    加Q[965546358]获取资源 第1章 课程导学 第2章 小程序开发入门 从几个方面介绍小程序开发相关的内容,包括小程序开发者账号注册.小程序开发流程.小程序开发规范.小程序常用的API,例如网络 ...

  5. 算法学习记录-图(DFS BFS)

    图: 目录: 1.概念 2.邻接矩阵(结构,深度/广度优先遍历) 3.邻接表(结构,深度/广度优先遍历) 图的基本概念: 数据元素:顶点 1.有穷非空(必须有顶点) 2.顶点之间为边(可空) 无向图: ...

  6. Hive 执行sql命令报错

    Failed with exception java.io.IOException:java.lang.IllegalArgumentException: java.net.URISyntaxExce ...

  7. luogu3760 [TJOI2017]异或和

    看这里 #include <iostream> #include <cstring> #include <cstdio> using namespace std; ...

  8. js 获取json对象的Key、value

    <script type="text/javascript"> getJson('age'); function getJson(key){ var jsonObj={ ...

  9. .NET重构(六):删除用户和结账的理解

    导读:这是第二回机房了,第一回不明不白,不清不楚的就过去了(相对),这一回,有了新的发现.就是在用户删除的时候,涉及到的一些逻辑问题,以及结账时的数据来源问题. 一.用户删除 问题:第一次机房,包括重 ...

  10. Codeforces #765D

    我在这道题上花了2个小时,仍没解出.理一下当时的思路,看看症结到底在哪里. 题意 用 $[n]$ 表示集合 $\{1,2,3,\dots, n\}$ . 3个函数 $f \colon [n] \to ...