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. SVN上传下载项目

    1 本机安装svn服务器 1.1    创建新库 创建分支, Trunk:主干, Tags:分支节点 Branches:分支 比如说我们现在tomcat出了6.0以后已经定版了,但是还得继续开发呀,开 ...

  2. Oracle备份恢复简单过程以及中间的坑.

    Oracle 冷备: 貌似需要dbca创建一致的oracle instance 服务器配置版本尽量相同,安装路径相同. 关闭Oracle服务 将oracle app 目录下的oradata以及有快速闪 ...

  3. python对redis的常用操作 下 (无序集合,有序集合)

    无序集合: 首先介绍增加,删除和获得所有元素的方法.我将会用第二部分来讨论集合的特殊操作: In [136]: x.sadd("challenge", 1,2,3,4,5,6,7, ...

  4. awk、sed、grep三大shell文本处理工具之sed的应用

    sed 流编辑器 对文本中的行,逐行处理 非交互式的编辑器 是一个编辑器 1.工作流程 1)将文件的第一行读入到自己的缓存空间(模式空间--pattern space),删除掉换行符 2)匹配,看一下 ...

  5. 【转】SpringMVC,获取request的几种方法,及线程安全性

    作者丨编程迷思 https://www.cnblogs.com/kismetv/p/8757260.html 概述 在使用Spring MVC开发Web系统时,经常需要在处理请求时使用request对 ...

  6. python之pygal:掷两个不同的骰子并统计大小出现次数

    代码示例: # 掷两个不同的骰子并统计大小出现次数 import pygal from die_class import Die die = Die(6) # 实例化一个六面的骰子对象 die_10 ...

  7. 2017ACM/ICPC广西邀请赛-重现赛

    HDU 6188 Duizi and Shunzi 链接:http://acm.hdu.edu.cn/showproblem.php?pid=6188 思路: 签到题,以前写的. 实现代码: #inc ...

  8. 2017ACM/ICPC亚洲区沈阳站-重现赛

    HDU 6222 Heron and His Triangle 链接:http://acm.hdu.edu.cn/showproblem.php?pid=6222 思路: 打表找规律+大数运算 首先我 ...

  9. FreeBSD ZFS

    FreeBSD ZFS https://www.cnblogs.com/hadex/p/6068476.html 参考資料 http://docs.oracle.com/cd/E37934_01/ht ...

  10. MT【13】三角函数求范围

    解答:AB显然正确,C中$a$取0时,解为三个,C 错误.我们主要看一下D 评:这里提供了一个处理$sin^2xcosx$的常见方法:平方,单变量后用算术几何不等式.