pom.xml
4.0.0 com.aa bb_redis 0.0.1-SNAPSHOT jar bb_redis http://maven.apache.org UTF-8 1.9.13 3.2.9.RELEASE junit junit 4.8.2 test org.hamcrest hamcrest-library 1.3 test org.testng testng 6.8.8 test javax.xml.bind jaxb-api 2.2.11 redis.clients jedis 2.4.2 org.springframework spring-oxm ${spring.version} org.springframework spring-test ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-tx ${spring.version} org.springframework.data spring-data-redis 1.3.1.RELEASE mysql mysql-connector-java 5.1.31 org.apache.commons commons-lang3 3.3.2 com.thoughtworks.xstream xstream 1.4.4 org.codehaus.jackson jackson-core-asl ${jackson.version} org.codehaus.jackson jackson-jaxrs ${jackson.version} org.codehaus.jackson jackson-mapper-asl ${jackson.version} org.codehaus.jackson jackson-xc ${jackson.version} org.codehaus.jackson jackson-jaxrs ${jackson.version} org.slf4j jcl-over-slf4j 1.6.1 commons-logging commons-logging 1.1.1 provided org.apache.maven.plugins maven-surefire-plugin true spring-releases http://repo.springsource.org/libs-release false
java代码方式配置Spring 环境:
package com.oreilly.springdata.redis; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import javax.sql.DataSource; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.OxmSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.transaction.PlatformTransactionManager; import com.zk.security_redis.entity.User; @Configuration public abstract class ApplicationConfig { @Bean public RedisConnectionFactory redisConnectionFactory() { JedisConnectionFactory cf = new JedisConnectionFactory(); cf.setHostName("127.0.0.1"); cf.setPort(6379); // cf.setPassword("superman"); cf.afterPropertiesSet(); return cf; } @Bean public PlatformTransactionManager transactionManager() throws SQLException { return new DataSourceTransactionManager(dataSource()); } @Bean public DataSource dataSource() throws SQLException { DriverManagerDataSource ds = new org.springframework.jdbc.datasource.DriverManagerDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/test"); ds.setUsername("test"); ds.setPassword("test"); Properties props = new Properties(); props.setProperty("useUnicode", "true"); ds.setConnectionProperties(props); return ds; } @Bean public RedisTemplate redisTemplate() { RedisTemplate rt = new RedisTemplate(); rt.setConnectionFactory(redisConnectionFactory()); rt.setEnableTransactionSupport(true); return rt; } private static MapjaxbContextHashMap = new ConcurrentHashMap (); @Bean public OxmSerializer oxmSerializer() throws Throwable { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); Map properties = new HashMap ();// 创建映射,用于设置Marshaller属性 properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // 放置xml自动缩进属性 properties.put(Marshaller.JAXB_ENCODING, "utf-8"); // 放置xml自动缩进属性 jaxb2Marshaller.setClassesToBeBound(User.class);// 映射的xml类放入JAXB环境中 jaxb2Marshaller.setMarshallerProperties(properties);// 设置Marshaller属性 return new OxmSerializer(jaxb2Marshaller, jaxb2Marshaller); } public static enum StringSerializer implements RedisSerializer { INSTANCE; public byte[] serialize(String s) throws SerializationException { return (null != s ? s.getBytes() : new byte[0]); } public String deserialize(byte[] bytes) throws SerializationException { if (bytes.length > 0) { return new String(bytes); } else { return null; } } } public static enum LongSerializer implements RedisSerializer { INSTANCE; public byte[] serialize(Long aLong) throws SerializationException { if (null != aLong) { return aLong.toString().getBytes(); } else { return new byte[0]; } } public Long deserialize(byte[] bytes) throws SerializationException { if (bytes.length > 0) { return Long.parseLong(new String(bytes)); } else { return null; } } } public static enum IntSerializer implements RedisSerializer { INSTANCE; public byte[] serialize(Integer i) throws SerializationException { if (null != i) { return i.toString().getBytes(); } else { return new byte[0]; } } public Integer deserialize(byte[] bytes) throws SerializationException { if (bytes.length > 0) { return Integer.parseInt(new String(bytes)); } else { return null; } } } }
测试用例代码:
package com.oreilly.springdata.redis; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import java.io.Serializable; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer; import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; import org.springframework.data.redis.serializer.OxmSerializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.zk.security_redis.entity.User; /** * @author Jon Brisbin */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {ApplicationConfig.class}) public class KeyValueSerializersTest { @Autowired RedisConnectionFactory connectionFactory; @Autowired OxmSerializer oxmSerializer; @Test public void testStringLongSerializers() throws Exception { RedisTemplateredis = new RedisTemplate (); redis.setConnectionFactory(connectionFactory); redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE); redis.setValueSerializer(ApplicationConfig.LongSerializer.INSTANCE); redis.afterPropertiesSet(); ValueOperations ops = redis.opsForValue(); String key = "spring-data-book:counter-test:hits"; ops.setIfAbsent(key, 1L); Long l = ops.increment(key, 1); redis.delete(key);; assertThat(l, is(greaterThan(0L))); } @Test public void testJdkSerialiable() { RedisTemplate redis = new RedisTemplate (); redis.setConnectionFactory(connectionFactory); redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE); redis.setValueSerializer(new JdkSerializationRedisSerializer()); redis.afterPropertiesSet(); ValueOperations ops = redis.opsForValue(); User user1 = new User(); user1.setUserName("user1"); user1.setAge(20); String key1 = "users/user1"; User user11 = null; long begin = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { ops.set(key1, user1); // user11 = (User) ops.get(key1); } long time = System.currentTimeMillis() - begin; System.out.println("jdk time:" + time); assertThat(user11.getUserName(), is("user1")); } @Test public void testJacksonSerialiable() { RedisTemplate redis = new RedisTemplate (); redis.setConnectionFactory(connectionFactory); redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE); redis.setValueSerializer(new JacksonJsonRedisSerializer (User.class)); redis.afterPropertiesSet(); ValueOperations ops = redis.opsForValue(); User user1 = new User(); user1.setUserName("user1"); user1.setAge(20); User user11 = null; String key1 = "json/user1"; long begin = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { ops.set(key1, user1); user11 = (User) ops.get(key1); } long time = System.currentTimeMillis() - begin; System.out.println("json time:" + time); assertThat(user11.getUserName(), is("user1")); } @Test public void testOxmSerialiable() throws Throwable { RedisTemplate redis = new RedisTemplate (); redis.setConnectionFactory(connectionFactory); redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE); redis.setValueSerializer(oxmSerializer); redis.afterPropertiesSet(); ValueOperations ops = redis.opsForValue(); User user1 = new User(); user1.setUserName("user1"); user1.setAge(20); User user11 = null; String key1 = "oxm/user1"; long begin = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { ops.set(key1, user1); user11 = (User) ops.get(key1); } long time = System.currentTimeMillis() - begin; System.out.println("oxm time:" + time); assertThat(user11.getUserName(), is("user1")); } @Test public void test1(){ RedisTemplate redis = new RedisTemplate (); redis.setConnectionFactory(connectionFactory); redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE); redis.setValueSerializer(new JacksonJsonRedisSerializer (User.class)); redis.afterPropertiesSet(); redis.setEnableTransactionSupport(true); redis.multi(); redis.boundValueOps("somevkey").increment(1); redis.boundZSetOps("somezkey").add("zvalue", 11); redis.discard(); } @Test @Transactional public void test2(){ RedisTemplate redis = new RedisTemplate (); redis.setConnectionFactory(connectionFactory); redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE); redis.setValueSerializer(new JacksonJsonRedisSerializer (User.class)); redis.afterPropertiesSet(); redis.setEnableTransactionSupport(true);//奇怪的是一定要再显示开启redistemplate的事务支持 redis.multi(); redis.boundValueOps("somevkey").increment(1); redis.boundZSetOps("somezkey").add("zvalue", 11); redis.exec(); } }