使用Spring + Jedis集成Redis

时间:2021-08-15 11:42:32

转自:http://my.oschina.net/u/866380/blog/521658

摘要

使用Spring和Jedis完成分片Redis的集成

一、集成环境

Tomcat7

JDK1.7

Jedis-2.7.2

Spring-4.1.6

二、资源依赖

(省略,网上很多)

三、集成过程

1、配置资源池

 这里使用Jedis的ShardedJedisPool来管理,我们定义该配置文件为:spring-redis.xml,全部内容如下:

<context:property-placeholder location="classpath:conf/properties/redis.properties"
ignore-unresolvable="true" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal">
<value>${redis.pool.maxActive}</value>
</property>
<property name="maxIdle">
<value>${redis.pool.maxIdle}</value>
</property>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
</bean> <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.uri}" />
</bean>
</list>
</constructor-arg>
</bean>

几个注意的点:

(1)如果你有多个数据源需要通过<context:property-placeholder管理,且不愿意放在一个配置文件里,那么一定要加上ignore-unresolvable=“true"

(2)注意新版的(具体从哪个版本开始不清楚,有兴趣可以查一下)JedisPoolConfig的property name,不是maxActive而是maxTotal,而且没有maxWait属性,建议看一下Jedis源码。

(3)ShardedJedisPool有多种构造函数,选择你需要的(具体看源码),示例中只初始化了一个分片,并使用了通过指定host的构造器(具体格式见下文),如果有集群,在下增加新的即可。

(4)当然,你的spring核心配置文件中得有<context:component-scan base-package="com.xxxx.xxx"/>扫描组件。

2、准备redis.properties,内容如下:

redis.pool.maxActive=200

redis.pool.maxIdle=50

redis.pool.minIdle=10

redis.pool.maxWaitMillis=20000

redis.pool.maxWait=300

redis.uri = redis://password@127.0.0.1:6379/0

redis.timeout=30000

这里要注意redis.uri的格式:redis://[密码]@[服务器地址]:[端口]/[db index]

建议大家使用这种方式,配置内容少,还能自定义db index,非常适合开发、测试和线上环境的切换

3、将spring-redis.xml加入web.xml的context中,如下:

contextConfigLocation

<param-value>classpath:conf/spring-redis.xml</param-value>

如果你有多个数据源通过spring管理(如mysql),则同时加载,如下:

contextConfigLocation
classpath:conf/spring-mybatis.xml,classpath:conf/spring-redis.xml

3、以上所有的配置已完成,接下来的代码的实现

 (1)推荐大家使用统一的类来管理Jedis实例的生成和回收,参考代码如下:JedisDataSourceImpl.class

@Repository("jedisDS")

public class JedisDataSourceImpl implements JedisDataSource {

private static final Logger LOG = LoggerFactory.getLogger(JedisDataSourceImpl.class);

@Autowired
private ShardedJedisPool shardedJedisPool; @Override
public ShardedJedis getRedisClient() {
ShardedJedis shardJedis = null;
try {
shardJedis = shardedJedisPool.getResource();
return shardJedis;
} catch (Exception e) {
LOG.error("[JedisDS] getRedisClent error:" + e.getMessage());
if (null != shardJedis)
shardJedis.close();
}
return null;
} @Override
public void returnResource(ShardedJedis shardedJedis) {
shardedJedis.close();
} @Override
public void returnResource(ShardedJedis shardedJedis, boolean broken) {
shardedJedis.close();
}

}

这里要注意的是Jedis实例的回收,从jedis2.6开始,原returnResource方式已经提示在后续版本中不再支持,所以不建议大家再用ShardedJedisPool里的returnResource和retureBrokenResource方法,虽然在2.7中还支持(毕竟是因为这两个方法存在漏洞)。

 (2)编写具体的Jedis操作类(片断):RedisClientTemplate.class

@Repository("redisClientTemplate")

public class RedisClientTemplate {

private static final Logger log = LoggerFactory.getLogger(RedisClientTemplate.class);

@Autowired
private JedisDataSource redisDataSource; public void disconnect() {
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
shardedJedis.disconnect();
} /**
* 设置单个值
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
String result = null; ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.set(key, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} /**
* 获取单个值
*
* @param key
* @return
*/
public String get(String key) {
String result = null;
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
} boolean broken = false;
try {
result = shardedJedis.get(key); } catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} public Boolean exists(String key) {
Boolean result = false;
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.exists(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} public String type(String key) {
String result = null;
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.type(key); } catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} /**
* 在某段时间后失效
*
* @param key
* @param seconds
* @return
*/
public Long expire(String key, int seconds) {
Long result = null;
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.expire(key, seconds); } catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} /**
* 在某个时间点失效
*
* @param key
* @param unixTime
* @return
*/
public Long expireAt(String key, long unixTime) {
Long result = null;
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.expireAt(key, unixTime); } catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} public Long ttl(String key) {
Long result = null;
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.ttl(key); } catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} public boolean setbit(String key, long offset, boolean value) { ShardedJedis shardedJedis = redisDataSource.getRedisClient();
boolean result = false;
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.setbit(key, offset, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} public boolean getbit(String key, long offset) {
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
boolean result = false;
if (shardedJedis == null) {
return result;
}
boolean broken = false; try {
result = shardedJedis.getbit(key, offset);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} public long setRange(String key, long offset, String value) {
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
long result = 0;
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.setrange(key, offset, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
} public String getRange(String key, long startOffset, long endOffset) {
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
String result = null;
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.getrange(key, startOffset, endOffset); } catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}

}

 (3)好了,接下来在你的业务代码里加载RedisClientTemplate.class就可以了。

使用Spring + Jedis集成Redis的更多相关文章

  1. Spring &plus; Jedis集成Redis(集群redis数据库)

    前段时间说过单例redis数据库的方法,但是生成环境一般不会使用,基本上都是集群redis数据库,所以这里说说集群redis的代码. 1.pom.xml引入jar <!--Redis--> ...

  2. Spring &plus; Jedis集成Redis(单例redis数据库)

    这几天没事,就把之前学习的redis代码整理一遍,废话不多说,上步骤. 1.pom.xml引入资源: <dependency> <groupId>org.springframe ...

  3. Spring&plus;Dubbo集成Redis的两种解决方案

    当下我们的系统数据库压力都非常大,解决数据库的瓶颈问题势在必行,为了解决数据库的压力等需求,我们常用的是各种缓存,比如redis,本文就来简单讲解一下如何集成redis缓存存储,附github源码. ...

  4. Spring Boot 2&period;X&lpar;六&rpar;:Spring Boot 集成Redis

    Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...

  5. (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...

  6. SpringBoot&lpar;十一&rpar;&colon; Spring Boot集成Redis

    1.在 pom.xml 中配置相关的 jar 依赖: <!-- 加载 spring boot redis 包 --> <dependency> <groupId>o ...

  7. 使用Spring Cache集成Redis

    SpringBoot 是为了简化 Spring 应用的创建.运行.调试.部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖 ...

  8. Spring Boot集成Redis集群(Cluster模式)

    目录 集成jedis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 集成spring-data-redis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 异常处理 同样的, ...

  9. spring boot集成redis的血泪史

    首先说明环境不是我搭建的,然后因项目需要添加redis的时候,麻烦来了.springboot 用的是1.5.9因为以前弄过redis,所以直接拿过来,麻烦了首先是莫名的错误,连项目都启动不了.但是最后 ...

随机推荐

  1. 面向对象to1

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  2. 网络请求报错:The resource could not be loaded because the App Transport Security policy requires the use of a secure connection&period;

    iOS9引入了新特性App Transport Security (ATS).详情:App Transport Security (ATS) 如果你想设置不阻止任何网络,只需要在info.plist文 ...

  3. HTML5 Canvas 高仿逼真 3D 布料图案效果

    HTML5 规范引进了很多新特性,其中最令人期待的之一就是 Canvas 元素,HTML5 Canvas 提供了通过 JavaScript 绘制图形的方法,非常强大.下面给大家分享一个 HTML5 C ...

  4. MariaDB的双主

     MariaDB(mysql)之主主复制   一.主主复制说明    MySQL主主复制结构区别于主从复制结构.在主主复制结构中,两台服务器的任何一台上面的数据库存发生了改变都会同步到另一台服务器上, ...

  5. React属性的3种设置方式

    一. 不推荐用setProps,因为以React的设计思想相悖,推荐以父组件向子组件传递属性的方式 二.3种用法的代码 1.键值对 <!DOCTYPE html> <html lan ...

  6. Android 模拟登陆 保存密码(信息)到手机中 文件信息读取

    package com.wuyou.login; import java.io.IOException; import java.util.Map; import android.app.Activi ...

  7. 编写高质量的JavaScript代码(一)

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 2016年6月加入腾讯,目前在SNG社交网络质量部从事内部平台工具的研发.熟悉PHP.JS.CSS,喜欢弹吉他 ...

  8. 服务器被疑似挖矿程序植入,发现以及解决过程(建议所有使用sonatype&sol;nexus3的用户清查一下)

    此次服务器被植入挖矿程序发现起来较为巧合,首先是上周三开始,我通过sonatype/nexus3搭建的仓库间歇性崩溃,但是每次重新start一下也能直接使用所以没有彻底清查,去docker logs里 ...

  9. Pandas&colon; 使用str&period;replace&lpar;&rpar; 进行文本清洗

    str.replace()可以一次处理一整个Series.str.replace()的正式形式为 Series.str.replace(pat, repl) ,其中pat为想要寻找的模式,一般为正则表 ...

  10. docker探索-swarm搭建docker集群&lpar;七&rpar;

    前言 Swarm 在 Docker 1.12 版本之前属于一个独立的项目,在 Docker 1.12 版本发布之后,该项目合并到了 Docker 中,成为 Docker 的一个子命令,docker s ...