欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring-data-redis配置事务

程序员文章站 2022-07-07 15:40:46
...

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.aa</groupId>
	<artifactId>bb_redis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>bb_redis</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<jackson.version>1.9.13</jackson.version>
		<spring.version>3.2.9.RELEASE</spring.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-library</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>6.8.8</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.2.11</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.3.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.31</version>
		</dependency>


		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>
		<dependency>
			<groupId>com.thoughtworks.xstream</groupId>
			<artifactId>xstream</artifactId>
			<version>1.4.4</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-jaxrs</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-xc</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-jaxrs</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<!-- 将现有的jakarta commons logging的调用转换成lsf4j的调用。 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.6.1</version>
		</dependency>
		<!-- Hack:确保commons-logging的jar包不被引入,否则将和jcl-over-slf4j冲突 -->
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<skipTests>true</skipTests>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>spring-releases</id>
			<url>http://repo.springsource.org/libs-release</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

 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 Map<Class, JAXBContext> jaxbContextHashMap = new ConcurrentHashMap<Class, JAXBContext>();

    @Bean
    public OxmSerializer oxmSerializer() throws Throwable
    {
        Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
        Map<String, Object> properties = new HashMap<String, Object>();// 创建映射,用于设置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<String>
    {
        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<Long>
    {
        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<Integer>
    {
        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
    {
        RedisTemplate<String, Long> redis = new RedisTemplate<String, Long>();
        redis.setConnectionFactory(connectionFactory);
        redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
        redis.setValueSerializer(ApplicationConfig.LongSerializer.INSTANCE);
        redis.afterPropertiesSet();
        
        

        ValueOperations<String, Long> 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<String, Serializable> redis = new RedisTemplate<String, Serializable>();
        redis.setConnectionFactory(connectionFactory);
        redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
        redis.setValueSerializer(new JdkSerializationRedisSerializer());
        redis.afterPropertiesSet();

        ValueOperations<String, Serializable> 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<String, Object> redis = new RedisTemplate<String, Object>();
        redis.setConnectionFactory(connectionFactory);
        redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
        redis.setValueSerializer(new JacksonJsonRedisSerializer<User>(User.class));
        redis.afterPropertiesSet();

        ValueOperations<String, Object> 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<String, Object> redis = new RedisTemplate<String, Object>();
        redis.setConnectionFactory(connectionFactory);
        redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);

        redis.setValueSerializer(oxmSerializer);
        redis.afterPropertiesSet();

        ValueOperations<String, Object> 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<String, Object> redis = new RedisTemplate<String, Object>();
        redis.setConnectionFactory(connectionFactory);
        redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
        redis.setValueSerializer(new JacksonJsonRedisSerializer<User>(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<String, Object> redis = new RedisTemplate<String, Object>();
        redis.setConnectionFactory(connectionFactory);
        redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
        redis.setValueSerializer(new JacksonJsonRedisSerializer<User>(User.class));
        redis.afterPropertiesSet();
        redis.setEnableTransactionSupport(true);//奇怪的是一定要再显示开启redistemplate的事务支持
        redis.multi();  
        redis.boundValueOps("somevkey").increment(1);  
        redis.boundZSetOps("somezkey").add("zvalue", 11);  
        redis.exec(); 
    }
}