http://blog.mkfree.com/posts/515835d1975a30cc561dc35d

spring-data-redis API:http://docs.spring.io/spring-data/redis/docs/1.5.1.RELEASE/api/

首先跟大家道歉,为什么呢?在不久之前,写了一篇http://blog.mkfree.com/posts/12,简单地使用是没有问题的,但如果在并发量高的时候,问题就会慢慢出现了,是什么问题呢?

当在高并发的情况下,向redis发出请求,每次操作都新建了一个连接,并且调用了一次连接就不释放也不重新使用,没有做连接池,虽然Redis的服务端,有一个机制是当客户端过一些时间没有操作时就关闭客户端连接。
这样有两个缺点:
1.在一定时间内,客户端连接数太多,在关闭连接时,也是非常消耗性能
2.达到一定的连接数时,服务端直接报错,连接数过多

经测试总结到以上两个问题.那应该怎么办呢?
其实,客户端连接可以放到一个连接池里,用完了,放回到连接池中,这样可以重复调用。。这样就可以限制一定数理的连接数,并且性能方面也优化了。。。后来我在官方上看到了spring data redis RedisTemplate,它封装了redis连接池管理的逻辑,业务代码无须关心获取,释放连接逻辑;spring redis同时支持了Jedis,Jredis,rjc 客户端操作;

下面就来看看具体的程序代码:

我首先定义了一些操作接口,我为了方便使用,重新封装下RedisTemplate.

RedisService 想要更多的操作自己在接口里添加啦

package com.mkfree.framework.common.redis;

import java.util.Set;

/**
* redis 的操作开放接口
*
* @author hk
*
* 2013-3-31 下午7:25:42
*/
public interface RedisService { /**
* 通过key删除
*
* @param key
*/
public abstract long del(String... keys); /**
* 添加key value 并且设置存活时间(byte)
*
* @param key
* @param value
* @param liveTime
*/
public abstract void set(byte[] key, byte[] value, long liveTime); /**
* 添加key value 并且设置存活时间
*
* @param key
* @param value
* @param liveTime
* 单位秒
*/
public abstract void set(String key, String value, long liveTime); /**
* 添加key value
*
* @param key
* @param value
*/
public abstract void set(String key, String value); /**
* 添加key value (字节)(序列化)
*
* @param key
* @param value
*/
public abstract void set(byte[] key, byte[] value); /**
* 获取redis value (String)
*
* @param key
* @return
*/
public abstract String get(String key); /**
* 通过正则匹配keys
*
* @param pattern
* @return
*/
public abstract Setkeys(String pattern); /**
* 检查key是否已经存在
*
* @param key
* @return
*/
public abstract boolean exists(String key); /**
* 清空redis 所有数据
*
* @return
*/
public abstract String flushDB(); /**
* 查看redis里有多少数据
*/
public abstract long dbSize(); /**
* 检查是否连接成功
*
* @return
*/
public abstract String ping(); }

RedisServiceImpl 接口实现类

package com.mkfree.framework.common.redis;

import java.io.UnsupportedEncodingException;
import java.util.Set; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; /**
* 封装redis 缓存服务器服务接口
*
* @author hk
*
* 2012-12-16 上午3:09:18
*/
@Service(value = "redisService")
public class RedisServiceImpl implements RedisService { private static String redisCode = "utf-8"; /**
* @param key
*/
public long del(final String... keys) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
long result = 0;
for (int i = 0; i < keys.length; i++) {
result = connection.del(keys[i].getBytes());
}
return result;
}
});
} /**
* @param key
* @param value
* @param liveTime
*/
public void set(final byte[] key, final byte[] value, final long liveTime) {
redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
connection.set(key, value);
if (liveTime > 0) {
connection.expire(key, liveTime);
}
return 1L;
}
});
} /**
* @param key
* @param value
* @param liveTime
*/
public void set(String key, String value, long liveTime) {
this.set(key.getBytes(), value.getBytes(), liveTime);
} /**
* @param key
* @param value
*/
public void set(String key, String value) {
this.set(key, value, 0L);
} /**
* @param key
* @param value
*/
public void set(byte[] key, byte[] value) {
this.set(key, value, 0L);
} /**
* @param key
* @return
*/
public String get(final String key) {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis(RedisConnection connection) throws DataAccessException {
try {
return new String(connection.get(key.getBytes()), redisCode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
});
} /**
* @param pattern
* @return
*/
public Setkeys(String pattern) {
return redisTemplate.keys(pattern); } /**
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.execute(new RedisCallback() {
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.exists(key.getBytes());
}
});
} /**
* @return
*/
public String flushDB() {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "ok";
}
});
} /**
* @return
*/
public long dbSize() {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
return connection.dbSize();
}
});
} /**
* @return
*/
public String ping() {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis(RedisConnection connection) throws DataAccessException { return connection.ping();
}
});
} private RedisServiceImpl() { } @Autowired
private RedisTemplate<string, string=""> redisTemplate; }

spring-context.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- 扫描注解Bean -->
<context:component-scan base-package="com.mkfree.framework.common.redis">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 初始化属性文件 -->
<bean id="propertyConfigurer" class="com.mkfree.framework.common.spring.MkfreePropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/project.properties</value>
</list>
</property>
</bean> <!-- 配置redis 缓存服务器 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<!-- <property name="password" value="${redis.password}" /> -->
</bean>
<!-- redis操作模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory">
<ref bean="connectionFactory"/>
</property>
</bean>
</beans>

最后就是简单的测试用例了 RedisServiceTest

package com.mkfree.framework.common.redis;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class RedisServiceTest { ApplicationContext app = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml");
RedisService redisService = (RedisService) app.getBean("redisService"); @Test
public void del() {
redisService.set("a1", "a1");
long result = redisService.del("a1");
Assert.assertEquals(1L, result);
} @Test
public void set() {
redisService.set("a1", "a1");
} @Test
public void get() {
redisService.set("a1", "a1");
String result = redisService.get("a1");
Assert.assertEquals("a1", result);
} }

spring data redis RedisTemplate操作redis相关用法的更多相关文章

  1. Spring中使用RedisTemplate操作Redis(spring-data-redis)

    RedisTemplate如何检查一个key是否存在? return getRedisTemplate().hasKey(key); 由一个问题,复习了一下redis 抄自: https://www. ...

  2. Java 使用Jedis和RedisTemplate操作Redis缓存(SpringBoot)

    package com.example.redis.controller; import com.example.redis.entity.User; import com.example.redis ...

  3. 使用Spring Data ElasticSearch+Jsoup操作集群数据存储

    使用Spring Data ElasticSearch+Jsoup操作集群数据存储 1.使用Jsoup爬取京东商城的商品数据 1)获取商品名称.价格以及商品地址,并封装为一个Product对象,代码截 ...

  4. spring-data-redis 中使用RedisTemplate操作Redis

    Redis 数据结构简介 Redis可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String(字符串).List(列表).Set(集合).Hash(散列)和 Zset(有序集合 ...

  5. SpringBoot 使用RedisTemplate操作Redis

    新版: import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.T ...

  6. spring spring data jpa save操作事务

    整合spring spring data jpa的时候,在save方法上加了@Transactional注解.此时调用springdatajpa save方法并不会真的把数据提交给数据库,而是缓存起来 ...

  7. [ecmagent][redis学习][1初识redis] python操作redis

    #1 连接redis # 连接redis -- import redis -- 使用端口连接redis conn = redis.Redis(host=) -- 使用套接字连接 r = redis.R ...

  8. Redis - Python操作Redis

    目录 Python操作Redis 一. Redis安装和基本使用 二. Python操作Redis API使用 1.操作模式 2.连接池 3.Django配置Redis 4.操作 Python操作Re ...

  9. python通过连接池连接redis,操作redis队列

    在每次使用redis都进行连接的话会拉低redis的效率,都知道redis是基于内存的数据库,效率贼高,所以每次进行连接比真正使用消耗的资源和时间还多.所以为了节省资源,减少多次连接损耗,连接池的作用 ...

随机推荐

  1. 通知(Notification) 、 应用间通信(一)

    1 使用通知中心发送消息 1.1 问题 当一个对象需要向多个接受者发送消息的,或者不用知道消息的接收者是谁,就可以使用IOS提供的NSNotificationCenter通知中心,本案例使NSNoti ...

  2. I.MX6 32G SD卡测试

    /*********************************************************************** * I.MX6 32G SD卡测试 * 说明: * 这 ...

  3. 《more effective c++》条款26 限制类对象的个数

    问题: 如何限制类对象的个数?比如1个,10个等等. 方法(1): 将类的构造函数定义为private,那么就无法实例化这个类了.但是如何创建1个对象出来?方法有2种: 1.声明一个友元函数,那么在友 ...

  4. MySQL优化—工欲善其事,必先利其器之EXPLAIN(转)

    最近慢慢接触MySQL,了解如何优化它也迫在眉睫了,话说工欲善其事,必先利其器.最近我就打算了解下几个优化MySQL中经常用到的工具.今天就简单介绍下EXPLAIN. 内容导航 id select_t ...

  5. MySQL数据库性能优化的关键参数(转)

    我们在进行数据库管理和开发中经常会遇到性能问题,这就涉及到MySQL的性能优化.通过在网络上查找资料和笔者自己的尝试,我认为以下系统参数是比较关键的: 关键参数一:back_log 要求 MySQL ...

  6. UIImage加载图片的两种方法区别

    Apple官方的文档为生成一个UIImage对象提供了两种方法加载图片: 1. imageNamed,其参数为图片的名字: 2. imageWithContentsOfFile,其参数也是图片文件的路 ...

  7. sgu546 Ternary Password

    题目链接:http://acm.sgu.ru/problem.php?contest=0&problem=546 这题还好,1Y,考虑情况周全,就没问题了,还好提交之前把想到的情况都测试了一遍 ...

  8. 基于Spring MVC的Web应用开发(三) - Resources

    基于Spring MVC的Web应用开发(3) - Resources 上一篇介绍了在基于Spring MVC的Web项目中加入日志,本文介绍Spring MVC如何处理资源文件. 注意到本项目的we ...

  9. leetcode 125. Valid Palindrome ----- java

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...

  10. CString用法总结

    概述:CString是MFC中提供的用于处理字符串的类,是一种很有用的数据类型. 它很大程度上简化了MFC中的许多操作,使得MFC在做字符串操作时方便了很多. 不管怎样,使用CString有很多的特殊 ...