码迷,mamicode.com
首页 > 编程语言 > 详细

Spring-Data-Redis存储对象(redisTemplate)

时间:2015-09-10 22:44:39      阅读:417      评论:0      收藏:0      [点我收藏+]

标签:

先给出配置,由于版本不同jedis的api不同,这里比较坑人,常常发生错误无从下手,如果是maven项目还好查看源码,如果是web项目那么就很麻烦,

<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.0.0</version>
</dependency>
<!-- spring-redis -->
<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-redis</artifactId>
	<version>1.0.0.RELEASE</version>
</dependency>

然后给出本人利用spring-data-redis封装的redis操作工具,原理就是对象转byte[],然后利用spring-data-redis进行存储,所以save形式为key(String->byte[])-value(Object->byte[]),get形式为key(byte[]->String)-value(byte[]->Object)

package com.zhxjz.framework.util.redis;

import java.io.Serializable;

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 com.zhxjz.framework.util.ApplicationContextUtil;
import com.zhxjz.framework.util.common.SerializeUtil;

public class SpringRedisUtil {

	@SuppressWarnings("unchecked")
	private static RedisTemplate<Serializable, Serializable> redisTemplate = 
				(RedisTemplate<Serializable, Serializable>) ApplicationContextUtil
						.getBean("redisTemplate");
	
	public static void save(final String key, Object value) {

		final byte[] vbytes = SerializeUtil.serialize(value);
		redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				connection.set(redisTemplate.getStringSerializer().serialize(key), vbytes);
				return null;
			}
		});
	}

	public static <T> T get(final String key, Class<T> elementType) {
		return redisTemplate.execute(new RedisCallback<T>() {
			@Override
			public T doInRedis(RedisConnection connection)
					throws DataAccessException {
				byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
				if (connection.exists(keybytes)) {
					byte[] valuebytes = connection.get(keybytes);
					@SuppressWarnings("unchecked")
					T value = (T) SerializeUtil.unserialize(valuebytes);
					return value;
				}
				return null;
			}
		});
	}
}

其中用到ApplicationContextUtil和SerializeUtil另外2个工具,

package com.zhxjz.framework.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

	private static ApplicationContext context;

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		ApplicationContextUtil.context = context;
	}

	public static ApplicationContext getContext() {
		return context;
	}

	public static Object getBean(String beanName) {
		return context.getBean(beanName);
	}

}
package com.zhxjz.framework.util.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {

	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

}

然后再给出springbean配置,

<?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:p="http://www.springframework.org/schema/p"
	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-4.0.xsd">

	<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}" />
		<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
	</bean>

	<bean id="jedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="${redis.hostname}" />
		<property name="port" value="${redis.port}" />
		<property name="password" value="${redis.password}" />
		<property name="poolConfig" ref="jedisPoolConfig" />
	</bean>

	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
		p:connection-factory-ref="jedisConnectionFactory" />

</beans>

<import resource="classpath:/SpringRedis.xml" />

下面是redis.properties

#redis config
redis.pool.maxActive=100
redis.pool.maxIdle=20
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true
redis.hostname=127.0.0.1
redis.port=6379
redis.password=

别忘了注册这个properties文件到PropertyPlaceholderConfigurer

用法:

写一个Controller进行测试:

package com.zhxjz.controller.testredis;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhxjz.framework.util.redis.SpringRedisUtil;
import com.zhxjz.model.testredis.TESTREDIS;

@Controller
@RequestMapping("/testredis")
public class TESTREDISController {
	
	@RequestMapping("/test.do")
	@ResponseBody
	public String test(TESTREDIS testredis) {
		SpringRedisUtil.save("mystr", testredis);
		return SpringRedisUtil.get("mystr", TESTREDIS.class).toString();
	}
	
}

最后把model都给出来

package com.zhxjz.model.testredis;

public class TESTREDIS implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	String testStr;
	int testInt;
	boolean testBool;

	public String getTestStr() {
		return testStr;
	}

	public void setTestStr(String testStr) {
		this.testStr = testStr;
	}

	public int getTestInt() {
		return testInt;
	}

	public void setTestInt(int testInt) {
		this.testInt = testInt;
	}

	public boolean isTestBool() {
		return testBool;
	}

	public void setTestBool(boolean testBool) {
		this.testBool = testBool;
	}

	public String toString() {
		return this.testStr + "|" + this.testInt + "|" + this.testBool;
	}

}

访问:http://localhost:8080/demo/testredis/test.do?testStr=testStr1&&testInt=1234&&testBool=true

技术分享

查看client:

技术分享

注意:

由于model需要转换为byte[],这里要求model必须implements java.io.Serializable,否则会报错。

Spring-Data-Redis存储对象(redisTemplate)

标签:

原文地址:http://my.oschina.net/u/555061/blog/504658

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!