Redis和Spring整合

Redis在这篇里就不做介绍了~以后系统的学学,然后整理写出来。

首先是环境的搭建

通过自己引包的方式,将redis和spring-redis的包引到自己的项目中,我项目中是通过pom引进的,如下(貌似版本都是写着篇博客时最新的):

 <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.1.RELEASE</version>
</dependency> <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

通过pom的依赖可以看出来,我用的Jedis作为我的Cilent。

配置Spring的配置文件

现在spring-boot框架大火,但是目前,我还是为了项目的可读性,使用配置文件的方式进行配置。以后有机会学习一下注解的方式,在总结出来。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 引入参数文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:init.properties</value>
</property>
</bean>
<!-- 使用redis缓存 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="true" />
</bean>
<bean id="jedis.shardInfo1" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.host}" />
<constructor-arg index="1" value="${redis.port}" />
<constructor-arg index="2" value="${redis.timeout}" />
<constructor-arg index="3" value="${redis.default.db}" />
<property name="password" value="${redis.pass}"></property>
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1" value="${redis.host}"/>
<constructor-arg index="2" value="${redis.port}" type="int"/>
<constructor-arg index="3" value="${redis.timeout}" type="int"/>
<constructor-arg index="4" value="${redis.pass}"/>
</bean>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<ref bean="jedis.shardInfo1" />
</list>
</constructor-arg>
</bean>
</beans>

大家可以看见,我这个配置文件写的比较奇葩...

因为我一共写了两个pool的bean,由于目前项目redis还是单机版本,所以我只是使用JedisPool这个进行之后的操作。ShardedJedisPool这个适用于分布式redis缓存的连接,但是我有一天突然发现没有flushDB的方法,我一着急,就换做了JedisPool,以后加强学习,把更加适用的方法总结出来。

RedisDataSource

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool; @Repository("jedisDS")
public class JedisDataSourceImpl implements JedisDataSource{
private static final Logger LOGGER = LoggerFactory.getLogger(JedisDataSourceImpl.class); @Autowired
private ShardedJedisPool shardedJedisPool;
@Autowired
private JedisPool jedisPool; @Override
public ShardedJedis getShardedRedisClient() {
ShardedJedis shardedJedis = null;
try{ shardedJedis = shardedJedisPool.getResource();
//shardedJedisPool.
return shardedJedis;
}catch (Exception e){
LOGGER.error("[JedisDS] getRedisClient error: "+e.getMessage());
if(null!=shardedJedis){
shardedJedis.close();
}
return null;
} } @Override
public Jedis getRedisClient() {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
return jedis;
}catch (Exception e){
if(null!=jedis){
jedis.close();
}
LOGGER.error("[JedisDS] getJedisClient error: "+e.getMessage());
}
return null;
} @Override
public void returnResource(ShardedJedis shardedJedis) {
shardedJedis.close();
} @Override
public void returnResource(ShardedJedis shardedJedis, boolean broken) {
shardedJedis.close();
} @Override
public void returnResource(Jedis jedis, boolean broken) {
jedis.close();
} }

上面的代码写了两种JedisPool和ShardedJedisPool两种方式

RedisCilentTamplate

这里整理了一些简单的方法,可以直接调用,可以直接参考一下


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis; @Repository("redisClientTemplate")
public class RedisClientTemplate {
private static final Logger log = LoggerFactory.getLogger(RedisClientTemplate.class); @Autowired
private JedisDataSource redisDataSource; public void disconnect() {
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
shardedJedis.disconnect();
} /**
* 设置单个值
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
String result = null; ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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.getShardedRedisClient();
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;
} public boolean del(String key){
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
boolean temp = false;
if (shardedJedis == null) {
return false;
}
boolean broken = false;
try { shardedJedis.del(key);
temp = true;
} catch (Exception e) {
log.error(e.getMessage(), e);
temp = false;
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
return temp;
} } public boolean fushAll(){
boolean temp = false;
Jedis jedis = redisDataSource.getRedisClient();
boolean broken = false;
try{
jedis.flushDB();
return true;
}catch (Exception e){
log.error(e.getMessage(), e);
temp = false;
broken = true;
}finally {
redisDataSource.returnResource(jedis, broken);
return temp;
}
} }

Redis和Spring整合的更多相关文章

  1. redis与spring整合实例

    1)首先是redis的配置. 使用的是maven工程,引入redis与spring整合的相关jar包 <!-- redis服务 start--> <dependency> &l ...

  2. 分布式缓存技术redis学习系列(五)——redis实战(redis与spring整合,分布式锁实现)

    本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...

  3. 分布式缓存技术redis系列(五)——redis实战(redis与spring整合,分布式锁实现)

    本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...

  4. redis系列之5----redis实战(redis与spring整合,分布式锁实现)

    本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...

  5. Redis跟Spring整合,sentinel模式

    普通模式整合 一.在pom.xml中引入redis的依赖 <dependency> <groupId>org.springframework.data</groupId& ...

  6. redis 与 spring整合 hash 增删改操作 list增删改操作

    本人,对于以前redis的学习是非常痛苦的!近期将以前的东西捡起来.以博客的形式存储,以便于以后快速捡起来,并和广大同胞一起分享! 1):简单介绍 redis 是基于C语言开发. redis是一个ke ...

  7. Redis + Jedis + Spring整合遇到的异常(转)

    项目中需要用到缓存,经过比较后,选择了redis,客户端使用jedis连接,也使用到了spring提供的spring-data-redis.配置正确后启动tomcat,发现如下异常: Caused b ...

  8. redis和spring整合使用

    第一步,在项目中加入redis的pom代码: <dependency> <groupId>redis.clients</groupId> <artifactI ...

  9. redis与spring整合·

    单机版: 配置spring配置文件applicationContext.xml <?xml version="1.0" encoding="UTF-8"? ...

随机推荐

  1. forEach、map、filter、some、every五个数组方法

    forEach() 方法对数组的每一个元素执行一次提供的函数. map() 方法创建一个新数组,其结果是该数组都执行一次函数,原函数保持不变. filter() 方法使指定函数测试数组的每一个元素,并 ...

  2. 《深入理解Java虚拟机》学习笔记之字节码执行引擎

    Java虚拟机的执行引擎不管是解释执行还是编译执行,根据概念模型都具有统一的外观:输入的是字节码文件,处理过程是字节码解析的等效过程,输出的是执行结果. 运行时栈帧结构 栈帧(Stack Frame) ...

  3. Fraction to Recurring Decimal leetcode

    Given two integers representing the numerator and denominator of a fraction, return the fraction in ...

  4. 百度地图API-覆盖物

    这两天一直在研究百度地图开放平台的各种好玩的东西,闲暇之余自己动手体验了一番,果然是妙趣横生,而且还可以自定义理想中的地图,不得不说,百度地图的开放平台为我们的应用提供了很多的便利,之前我们已经学习了 ...

  5. 【常见踩坑】USB调试安装失败(Installation failed with message INSTALL_CANCELED_BY_USER)

    一.写在前面 最近一直在忙活着项目重构,忙活了一个多月(那是天天加班,不分昼夜呀,ps:这不是我司要求的哈),终于把沉积了三四年的老项目给重构了,目前在测试阶段,也总算有了点闲时来跟大家分享分享一些问 ...

  6. Xamarin.Android Binding篇

    前言 趁着失业了,闲着没事儿学习了下Xamarin.Android binding,在以往的开发中,我相信很多人都遇到过binding的坑,也不例外, 我也踩了很多雷,好在认识了个大佬,指导了很多  ...

  7. jsp想js,action传值

    1.struts2 action如何向JSP的JS函数传值 action中定义变量 public class TestAction extends ActionSupport implements S ...

  8. Android中的几种多线程实现

    有以下几种方式: 1)Activity.runOnUiThread(Runnable) 2)View.post(Runnable) ;View.postDelay(Runnable , long) 3 ...

  9. mysql索引使用技巧及注意事项

    一.索引的作用 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,遇到最多的,也是最容易出问题的,还是一些复杂的查询操作,所以查询语句的优化显然是重中之重. 在数据 ...

  10. Android布局优化之层级优化

    程序的每个组件和 Layout 都需要经过初始化.布局和绘制,如果布局嵌套层次过深,就会导致加载操作更为耗时,更严重的话还可能导致内存溢出.本节我们学习使用两个工具来检查和优化 Layout. Hie ...