spring整合redis-----ShardedJedisPool实现
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实现的更多相关文章
- 网站性能优化小结和spring整合redis
现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...
- Spring整合Redis&JSON序列化&Spring/Web项目部署相关
几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...
- spring整合redis之hello
1.pom.xml文件 <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.spri ...
- Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object
我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!
- 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 ...
- Spring整合redis实现key过期事件监听
打开redis服务的配置文件 添加notify-keyspace-events Ex 如果是注释了,就取消注释 这个是在以下基础上进行添加的 Spring整合redis:https://www. ...
- Spring整合redis,通过sentinel进行主从切换
实现功能描述: redis服务器进行Master-slaver-slaver-....主从配置,通过2台sentinel进行failOver故障转移,自动切换,采用该代码完全可以直接用于实际生产环境. ...
- (转)Spring整合Redis作为缓存
采用Redis作为Web系统的缓存.用Spring的Cache整合Redis. 一.关于redis的相关xml文件的写法 <?xml version="1.0" ...
- spring整合redis使用RedisTemplate的坑Could not get a resource from the pool
一.背景 项目中使用spring框架整合redis,使用框架封装的RedisTemplate来实现数据的增删改查,项目上线后,我发现运行一段时间后,会出现异常Could not get a resou ...
- SpringBoot开发二十-Redis入门以及Spring整合Redis
安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis. 代码实现 Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个 Redis 的常用命 ...
随机推荐
- jQuery(六)
$下常用方法 $().xxx:只能给jq对象用 $.xxx不仅可以给jq用也可以给原生js用,叫做工具方法 $.type() <script> $(function(){ var a= n ...
- modern effective C++ -- Deducint Types
1. 理解模板类型推导 1. expr是T& template<typename T> void f(T & param); // 我们声明如下变量 int x = 27; ...
- ubuntu安装命令
sudo apt-get update 更新源sudo apt-get install package 安装包sudo apt-get remove package 删除包sudo apt-cach ...
- 操作系统+编程语言的分类+执行python程序的两种方式+变量
1.什么是操作系统? 操作系统就是一个协调\管理\控制计算机硬件资源与软件资源的一个控制程序. 2.为何要操作系统? a.把复杂的硬件操作封装成简单的功能\接口用来给用户或者程序来使用(文件) b.把 ...
- linux shell $ 特殊变量
$0 #Shell本身的文件名 $1-$n #添加到Shell的各参数值.$1是第1参数.$2是第2参数… $* #所有参数列表.如"$*"用「"」括起来的情 ...
- SSM三大框架整合配置(Spring+SpringMVC+MyBatis)
web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi=" ...
- liunx上安装MySQL一个非常简单的方法
1.官网下载yum源 https://www.mysql.com/ 2.把yum源包上传到linux,安装. 执行命令安装 [root@bogon ~]# yum localinstall mysql ...
- maven 聚合的含义是父类打包 ,清理等 则子类自动打包;也就是一键打包 方便服务
maven 聚合的含义是父类打包 ,清理等 则子类自动打包:也就是一键打包 方便服务
- BZOJ4517[Scoi2016]美味——主席树
题目描述 一家餐厅有 n 道菜,编号 1...n ,大家对第 i 道菜的评价值为 ai(1≤i≤n).有 m 位顾客,第 i 位顾客的期 望值为 bi,而他的偏好值为 xi .因此,第 i 位顾客认为 ...
- $Min\_25$筛学习笔记
\(Min\_25\)筛学习笔记 这种神仙东西不写点东西一下就忘了QAQ 资料和代码出处 资料2 资料3 打死我也不承认参考了yyb的 \(Min\_25\)筛可以干嘛?下文中未特殊说明\(P\)均指 ...