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. LeetCode(9)Palindrome Number

    题目: Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could neg ...

  2. IntelliJ IDEA 类和方法注释的生成以及Javadoc的简单使用记录

    idea,设置类注释和,方法注释的常见的设置方法(不同的版本设置方法有所偏差,简单记录一些目前自己在使用的方法,) 方法注释:在keyMap中搜索Fix doc comment ,后点击右键设置一个快 ...

  3. Python 多级目录选择+一键正反排序

    效果如图所示,可以根据条件来选择对象 cat pc.py #!/usr/bin/pythonfrom flask import Flask,render_template,request,redire ...

  4. centos7中的网卡一致性命名规则、网卡重命名方法

    一致性网络设备命名(Consistent Network Device Naming) 背景介绍: 在centos5的时候,我们习惯了eth0这样的网络设备命名,在centos6发现网络设备变成了em ...

  5. Leetcode 335.路径交叉

    路径交叉 给定一个含有 n 个正数的数组 x.从点 (0,0) 开始,先向北移动 x[0] 米,然后向西移动 x[1] 米,向南移动 x[2] 米,向东移动 x[3] 米,持续移动.也就是说,每次移动 ...

  6. [BZOJ4506] [Usaco2016 Jan]Fort Moo(DP?)

    传送门 总之可以先预处理出来每个位置最多往上延伸多少 枚举两行,看看夹在这两行中间的列最大能构成多大的矩形 可以看出,必须得在一个两行都没有X的区间才有可能构成最大的答案 那么可以把这些区间处理出来, ...

  7. spring中quartz的使用。【转http://www.cnblogs.com/kay/archive/2007/11/02/947372.html】

    注:从spring3到spring4改变 org.springframework.scheduling.quartz.CronTriggerBean org.springframework.sched ...

  8. 回顾基础知识,类,fbv,cbv

    一 类中绑定方法的传参,不需要self class Foo(object): def __init__(self,name): self.name = name def foo(self,x): se ...

  9. poj 2987 Firing

    Firing Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 10696   Accepted: 3226 Descript ...

  10. leetcode 331. Verify Preorder Serialization of a Binary Tree

    传送门 331. Verify Preorder Serialization of a Binary Tree My Submissions QuestionEditorial Solution To ...