Spring-Data-Redis存儲對象(redisTemplate)

先給出配置,因爲版本不一樣jedis的api不一樣,這裏比較坑人,經常發生錯誤無從下手,若是是maven項目還好查看源碼,若是是web項目那麼就很麻煩,java

<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>

整個目錄結構,web

而後給出本人利用spring-data-redis封裝的redis操做工具,原理就是對象轉byte[],而後利用spring-data-redis進行存儲,因此save形式爲key(String->byte[])-value(Object->byte[]),get形式爲key(byte[]->String)-value(byte[]->Object)redis

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個工具,spring

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);
		}
	}

}

而後再給出SpringRedis.xml配置,shell

<?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" />
api

下面是redis.propertiesapp

#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文件到PropertyPlaceholderConfigurermaven

用法:ide

寫一個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,不然會報錯。

相關文章
相關標籤/搜索