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(); } }
相关推荐
9. **Spring Boot集成**:Spring Data Redis与Spring Boot的深度整合,使得配置变得更加简洁,只需要少量的配置就能快速搭建起Redis连接。 10. **源码分析**:`spring-data-redis-1.7.6.RELEASE-sources.jar`包含了...
接着,在Spring的配置类中定义RedisConnectionFactory和RedisTemplate,这两个组件是Spring Data Redis的核心,它们负责建立与Redis的连接并执行各种操作。 ```java @Configuration @EnableCaching public class ...
Spring-data-redis是Spring框架提供的用于操作Redis的库,它支持与Redis集群的交互。在Spring应用中,可以使用`JedisCluster`类来操作Redis集群。 1. **依赖引入**:在项目中添加Spring-data-redis和Jedis的相关...
7. **Spring Boot集成**:在Spring Boot应用中,Spring Data Redis可以通过自动配置轻松地启用,只需要在pom.xml或build.gradle中添加依赖,并在application.properties或application.yml中设置相关配置。...
此外,Spring Data Redis还支持事务(Transactions)和发布/订阅(Pub/Sub)模式。通过`TransactionOperations`接口,开发者可以执行多条命令并在一个原子操作中提交或回滚。发布/订阅模式允许实时通信,通过`...
Spring Data Redis的核心功能包括连接池管理、命令执行、事务支持、发布/订阅、持久化等。其主要组件有RedisTemplate和StringRedisTemplate,它们是操作Redis的关键工具。RedisTemplate提供了一般化的操作接口,而...
6. **事务支持**:尽管 Redis 自身不支持传统的关系型数据库事务,但 Spring Data Redis 提供了一种模拟事务的机制,通过批处理操作确保一组操作的原子性。 7. **KeySpace Notifications**:该版本还支持 Redis 的 ...
2. **数据操作API**:Spring Data Redis提供了丰富的API,如操作键值、哈希、列表、集合和有序集合的方法,以及事务处理、管道传输等功能。这些API使得开发者无需直接接触Redis命令,即可完成复杂的数据操作。 3. *...
此外,Spring Data Redis还集成了Spring Framework的事务管理功能,允许开发者在Redis操作中实现事务控制。尽管Redis本身不支持ACID(原子性、一致性、隔离性和持久性)事务,但Spring Data Redis通过回滚策略和...
6. **事务支持**:虽然Redis本身不支持ACID事务,但Spring Data Redis提供了有限的事务管理能力,比如`RedisTransactionManager`,可以在多个操作之间保持一致性。 7. **Redis Cache**:Spring框架的缓存抽象可以与...
通过以上配置,Spring-data-redis就能在Spring项目中发挥作用,提供方便、稳定且功能丰富的Redis操作。开发者可以利用它提供的各种操作接口,轻松实现数据的增删查改,以及更复杂的数据结构操作,比如发布/订阅、...
Spring Data Redis模块提供了与Redis交互的抽象层,使得开发者可以轻松地利用Redis的功能,如键值存储、发布/订阅、事务等。 接下来是Jedis。Jedis是Redis官方推荐的Java客户端,提供了丰富的API来执行各种Redis...
综上所述,Spring Data Redis 不仅提供了对 Redis 的全面支持,还极大地简化了 Redis 的使用难度,使得开发者能够专注于业务逻辑而不是复杂的 Redis 配置细节。无论是初学者还是经验丰富的开发者,都可以从中...
6. **事务支持**:尽管Redis本身不支持ACID事务,但Spring Data Redis提供了一种模拟事务的方式,允许你在多个操作之间保持一致性。 7. **Lettuce客户端**:除了Jedis,Spring Data Redis也支持另一个Redis客户端...
3. **高级功能**:Spring Data Redis还支持Redis的高级特性,如发布/订阅(Publish/Subscribe)、事务(Transaction)、lua脚本(Lua Scripting)以及地理空间操作(Geo-Spatial Operations)。 4. **Reactive编程**:随着...
本项目"springboot_SpringDataRedis_redis.zip"正是关于如何在Spring Boot应用中集成Redis,并利用Spring Data Redis库进行数据操作的示例。 首先,让我们深入理解Spring Boot与Redis的集成。Spring Boot通过其...
Spring Data Redis是一个强大的Java库,它为开发人员提供了一种简单的方式来利用Redis内存数据存储进行数据操作。在本文中,我们将深入探讨Spring Data Redis的基本概念、功能和如何通过一个小例子来实现其应用。 ...
8. Redis事务:介绍如何使用Spring的@Transactional注解来管理Redis的事务。 9. 管道(Pipelining):管道技术用于减少网络延迟,提高Redis操作效率。 10. Redis脚本:Redis支持使用Lua脚本执行操作,文档中可能...
spring-data-redis 是 Spring大家族的一部分,提供了在 Spring 应用中通过简单的配置访问 Redis 服务,对 Redis 底层开发包(Jedis, JRedis, and RJC)进行了高度封装。RedisTemplate 提供了 Redis 各种操作、异常...