设为首页 收藏本站
查看: 767|回复: 0

[经验分享] Spring data redis的简单应用

[复制链接]

尚未签到

发表于 2016-12-20 06:41:03 | 显示全部楼层 |阅读模式
  这里给出了一个简单封装的 RedisService 服务类。

package com.wanmei.redis.test.service;
import java.util.Collection;
import java.util.Set;
/**
* <pre>
* @author xuepeng<br>
* @date 2013年12月25日<br>
* @Copyright wanmei.com [2004-2013]<br>
* @Description redis 的服务接口
* </pre>
*/
public interface RedisService {
/**
* <pre>
* 通过key删除
* @param keys
* @return 被删除的记录数
* </pre>
*/
public long delete(String... keys);
/**
* <pre>
* 通过keys删除
* @param keys
* @return 被删除的记录数
* </pre>
*/
public long delete(Collection<String> keys);
/**
* <pre>
*  @param key
*  @param value
*  @param activeTime 秒
*  @return 添加key value 并且设置存活时间
* </pre>
*/
public boolean set(byte[] key, byte[] value, long activeTime);
/**
* <pre>
* @param key
* @param value
* @param activeTime 秒
* @return 添加key value 并且设置存活时间
* </pre>
*/
public boolean set(String key, String value, long activeTime);
/**
* <pre>
*  @param key
*  @param value
*  @return 添加key value
* </pre>
*/
public boolean set(String key, String value);
/**
* <pre>
*  @param key
*  @param value
*  @return 添加key value
* </pre>
*/
public boolean set(byte[] key, byte[] value);
/**
* <pre>
* @param key
* @return 获得value
* </pre>
*/
public String get(String key);
/**
* <pre>
* @param pattern
* @return 通过正则匹配keys
* </pre>
*/
public Set<String> matchKeys(String pattern);
/**
* <pre>
* @param key
* @return 检查key是否已经存在
* </pre>
*/
public boolean exists(String key);
/**
* <pre>
* @return 清空所有数据
* </pre>
*/
public boolean flushDB();
}


package com.wanmei.redis.test.service.impl;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
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;
import com.wanmei.redis.test.service.RedisService;
/**
* <pre>
* @author xuepeng<br>
* @date 2013年12月25日<br>
* @Copyright wanmei.com [2004-2013]<br>
* @Description Redis 服务实现类
* </pre>
*/
@Service(value = "redisService")
public class RedisServiceImpl implements RedisService {
private static final String CHARSET = "UTF8";
@Autowired
private RedisTemplate<String, Serializable> redisTemplate;
public void setRedisTemplate(
RedisTemplate<String, Serializable> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public boolean set(final byte[] key, final byte[] value,
final long activeTime) {
return redisTemplate.execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
boolean rs = true;
connection.set(key, value);
if (activeTime > 0) {
rs = connection.expire(key, activeTime);
}
return rs;
}
});
}
@Override
public boolean set(String key, String value, long activeTime) {
return this.set(key.getBytes(), value.getBytes(), activeTime);
}
@Override
public boolean set(String key, String value) {
return this.set(key, value, 0L);
}
@Override
public boolean set(byte[] key, byte[] value) {
return this.set(key, value, 0L);
}
@Override
public String get(final String key) {
return redisTemplate.execute(new RedisCallback<String>() {
public String doInRedis(RedisConnection connection)
throws DataAccessException {
try {
byte[] value = connection.get(key.getBytes());
return value == null ? "" : new String(value, CHARSET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
});
}
@Override
public Set<String> matchKeys(String pattern) {
return redisTemplate.keys(pattern);
}
@Override
public boolean exists(final String key) {
return redisTemplate.execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
return connection.exists(key.getBytes());
}
});
}
@Override
public boolean flushDB() {
return redisTemplate.execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
connection.flushDb();
return true;
}
});
}
@Override
public long delete(final Collection<String> keys) {
return redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
long result = 0;
for (String key : keys) {
result = connection.del(key.getBytes());
}
return result;
}
});
}
@Override
public long delete(final String... keys) {
Collection<String> cols = new ArrayList<String>();
for (String key : keys) {
cols.add(key);
}
return this.delete(cols);
}
}


package com.wanmei.redis;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.wanmei.redis.test.bean.User;
import com.wanmei.redis.test.service.RedisService;
/**
* <pre>
* @author xuepeng<br>
* @date 2013年12月25日<br>
* @Copyright wanmei.com [2004-2013]<br>
* @Description 单元测试类
* </pre>
*/
public class UserServiceTest {
private ApplicationContext app;
private RedisService redisService;
@Before
public void before() throws Exception {
app = new ClassPathXmlApplicationContext(
"com/wanmei/redis/spring-ctx-application.xml");
redisService = (RedisService) app.getBean("redisService");
}
@Test
public void crud() {
for (;;) {
System.out.println(Strings.repeat("-", 50));
// -------------- Create ---------------
String address1 = Strings.repeat("上海", 50);
User user = new User();
user.setAddress(address1);
user.setUid("u123456");
String key = toJSONString(user);
String value = key;
long beforeSave = System.currentTimeMillis();
redisService.set(key, value);
System.out.println("save consumes : "
+ (System.currentTimeMillis() - beforeSave));
// ---------------Read ---------------
long beforeRead = System.currentTimeMillis();
String r1 = redisService.get(key);
System.out.println("read consumes : "
+ (System.currentTimeMillis() - beforeRead));
user = parse(r1, User.class);
System.out.println("address1=" + user.getAddress());
assertEquals(address1, user.getAddress());
// --------------Update ------------
String address2 = "北京";
user.setAddress(address2);
final String key1 = toJSONString(user);
String value1 = key1;
redisService.set(key1, value1);
String r2 = redisService.get(key1);
user = parse(r2, User.class);
System.out.println("address2Save=" + user.getAddress());
assertEquals(address2, user.getAddress());
// --------------Delete ------------
long beforeDelete = System.currentTimeMillis();
long rs = redisService.delete(key1);
System.out.println("delete record's count : " + rs);
System.out.println("delete consumes : "
+ (System.currentTimeMillis() - beforeDelete));
String r3 = redisService.get(key1);
System.out.println("addressdel=" + r3);
assertEquals("", r3);
// -------------exist----------------
user.setAddress("呵呵");
user.setUid("哈哈哈");
String lastKey = user.toString();
redisService.set(lastKey, lastKey);
boolean r4 = redisService.exists(lastKey);
assertEquals(true, r4);
// -------------flushDB----------------
System.out.println("flushDB:" + redisService.flushDB());
String r5 = redisService.get(lastKey);
assertEquals("", r5);
}
}
private static String toJSONString(Object t) {
return JSON.toJSONString(t);
}
private static <T> T parse(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
}
}
  下面是Spring的XML配置:
  spring-ctx-application.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:p="http://www.springframework.org/schema/p" xmlns:sec="http://www.springframework.org/schema/security"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<context:annotation-config />
<context:component-scan base-package="com.wanmei.redis"></context:component-scan>
<context:property-placeholder
location="classpath:com/wanmei/redis/test/config/redis.properties" />
<!-- 对象池配置: -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxActive" value="${redis.pool.maxActive}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="maxWait" value="${redis.pool.maxWait}" />
</bean>
<!-- 工厂实现: -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.ip}" />
<property name="port" value="${redis.port}" />
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>
<!--模板类: -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnectionFactory" />

</beans>

  redis.properties

redis.pool.maxActive=1000
redis.pool.maxIdle=100
redis.pool.maxWait=500
redis.ip=test-server
redis.port=6379

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-316545-1-1.html 上篇帖子: redis-cli 命令总结 下篇帖子: Spring-data-redis: 分布式队列
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表