redis是一个非常优秀的缓存框架,良好的api,强悍的性能,是现在非常非常火的缓存框架。下面来介绍一下spring中是如何整合redis的

分析:

  • 需要引入依赖
  • 需要配置连接池,就是一个xml文件,然后参数写在properties中
  • 需要写一个工具类,主要方法有,从这个连接池中得到redis资源,销毁redis资源。
  • 需要再写一个service,这个就是具体的得到redis实例之后,保存缓存save方法,取得缓存get方法。具体是按照自己业务逻辑来实现。比如说key如何生成了,反正最后都是用的一个redis的api。这里就简单演示一下。

pom.xml

<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
<type>jar</type>
</dependency>

redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:redis.properties" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" /> <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton" >
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}"/>
<constructor-arg name="port" value="${redis.port}"/>
<constructor-arg name="timeout" value="${redis.timeout}"/>
</bean>
</list>
</constructor-arg>
</bean> </beans>
redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.timeout=3000
RedisPool.java
package com.mmall.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool; import javax.annotation.Resource; /**
* Created by 敲代码的卡卡罗特
* on 2018/4/1 14:21.
*/
@Service("redisPool")
@Slf4j
public class RedisPool {
@Resource(name = "shardedJedisPool")
private ShardedJedisPool shardedJedisPool; public ShardedJedis instance() {
return shardedJedisPool.getResource();
}
public void safeClose(ShardedJedis shardedJedis) {
try {
if (shardedJedis != null) {
shardedJedis.close();
}
} catch (Exception e) {
log.error("return redis resource exception", e);
}
}
}

CacheService.java


package com.mmall.service;

import com.google.common.base.Joiner;
import com.mmall.beans.CacheKeyConstants;
import com.mmall.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis; import javax.annotation.Resource; /**
* Created by 敲代码的卡卡罗特
* on 2018/4/1 14:22.
*/
@Service
@Slf4j
public class SysCacheService {
@Resource(name = "redisPool")
private RedisPool redisPool; //保存value
public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix) {
saveCache(toSavedValue, timeoutSeconds, prefix, null);
}
//保存value
public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
if (toSavedValue == null) {
return;
}
ShardedJedis shardedJedis = null;
try {
String cacheKey = generateCacheKey(prefix, keys);
shardedJedis = redisPool.instance();
shardedJedis.setex(cacheKey, timeoutSeconds, toSavedValue);
} catch (Exception e) {
log.error("save cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
} finally {
redisPool.safeClose(shardedJedis);
}
}
//如何生成key
private String generateCacheKey(CacheKeyConstants prefix, String... keys) {
String key = prefix.name();
if (keys != null && keys.length > 0) {
key += "_" + Joiner.on("_").join(keys);
}
return key;
}
//根据key得到value
public String getFromCache(CacheKeyConstants prefix, String... keys) {
ShardedJedis shardedJedis = null;
String cacheKey = generateCacheKey(prefix, keys);
try {
shardedJedis = redisPool.instance();
String value = shardedJedis.get(cacheKey);
return value;
} catch (Exception e) {
log.error("get from cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
return null;
} finally {
redisPool.safeClose(shardedJedis);
}
} }

然后在application.xml中引入redis的配置文件就ok

<import resource="redis.xml" />
 

spring整合redis-----ShardedJedisPool实现的更多相关文章

  1. 网站性能优化小结和spring整合redis

    现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...

  2. Spring整合Redis&JSON序列化&Spring/Web项目部署相关

    几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...

  3. spring整合redis之hello

    1.pom.xml文件 <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.spri ...

  4. Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object

    我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!

  5. Redis的安装以及spring整合Redis时出现Could not get a resource from the pool

    Redis的下载与安装 在Linux上使用wget http://download.redis.io/releases/redis-5.0.0.tar.gz下载源码到指定位置 解压:tar -xvf ...

  6. Spring整合redis实现key过期事件监听

    打开redis服务的配置文件   添加notify-keyspace-events Ex  如果是注释了,就取消注释 这个是在以下基础上进行添加的 Spring整合redis:https://www. ...

  7. Spring整合redis,通过sentinel进行主从切换

    实现功能描述: redis服务器进行Master-slaver-slaver-....主从配置,通过2台sentinel进行failOver故障转移,自动切换,采用该代码完全可以直接用于实际生产环境. ...

  8. (转)Spring整合Redis作为缓存

           采用Redis作为Web系统的缓存.用Spring的Cache整合Redis. 一.关于redis的相关xml文件的写法 <?xml version="1.0" ...

  9. spring整合redis使用RedisTemplate的坑Could not get a resource from the pool

    一.背景 项目中使用spring框架整合redis,使用框架封装的RedisTemplate来实现数据的增删改查,项目上线后,我发现运行一段时间后,会出现异常Could not get a resou ...

  10. SpringBoot开发二十-Redis入门以及Spring整合Redis

    安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis. 代码实现 Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个 Redis 的常用命 ...

随机推荐

  1. 正则表达式(java)

    概念: 正则表达式,又称规则表达式.(英语:Regular Expression,在代码中常简写为regex.regexp或RE),计算机科学的一个概念. 正则表通常被用来检索.替换那些符合某个模式( ...

  2. tensorflow在windows下的安装

    1.python 的安装 这里我选择的是Anaconda4.2,附上下载链接https://www.continuum.io/downloads 2.测试python安装是否成功 在cmd中输入pyt ...

  3. mybatis集成redis

    系统原生集成的Ehcache, 但是监控需要(version 2.7),Ehcache Monitor http://www.ehcache.org/documentation/2.7/operati ...

  4. 产品激活 比如Windows激活 , office激活 等激活的原理是什么? KMS等激活工具安全吗?

    什么是密钥管理服务 (KMS)? 密钥管理服务 (KMS) 允许在本地网络上激活产品.这样,单台计算机不必连接至 Microsoft 便可激活产品.需要将一台计算机配置为 KMS 主机.管理员必须为 ...

  5. Qt__文件打开保存对话框(QFileDialog)

    转自豆子空间 使用QFileDialog有两种方法,一种是比较简单的使用"静态函数法",另一种是可以自定义各个细节的"构造函数法". 静态函数法 修改MainW ...

  6. parent()、parents()和parentsUntil()的区别

    1.parent() 返回被选元素的直接父元素,该方法只会向上一级对 DOM 树进行遍历: 2.parents() 返回被选元素的所有祖先元素,它一路向上直到文档的根元素 (<html>) ...

  7. linux学习之centos(四):git的安装

    整个流程如下:(参考文章:linux安装git方法) [carsonzhu@localhost 桌面]$ wget https://github.com/git/git/archive/v2.8.3. ...

  8. P3760 [TJOI2017]异或和

    题目描述 在加里敦中学的小明最近爱上了数学竞赛,很多数学竞赛的题都是与序列的连续和相关的.所以对于一个序列,求出它们所有的连续和来说,小明觉得十分的简单.但今天小明遇到了一个序列和的难题,这个题目不仅 ...

  9. day30 hashlib模块

    hashlib 提供摘要算法 最常见的就是MD5,当然一般来说MD5已经被足够了 不管算法多不一样,但是摘要的功能是不变的 对于相同的字符串进行摘要,使用同一个算法得到的值总是不变的 不同算法的话,会 ...

  10. HTM L百度地图API 自定义工具地图实例

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...