使用底层API:RedisConnectionFactory
和RedisConnection
可以直接操作Redis,下面是一个简单的例子:
Maven依赖
<properties>
<jedis.version>2.9.0</jedis.version>
<spring.redis.version>1.8.2.RELEASE</spring.redis.version>
</properties>
<dependencies>
<!-- jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<!-- spring-data-redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring.redis.version}</version>
</dependency>
</dependencies>
配置redis.properties
redis.host=127.0.0.1
redis.port=6379
配置Spring-data-redis.xml
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 读取properties文件 -->
<bean id="propertyConfigurerForProject1"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath*:redis.properties</value>
</list>
</property>
</bean>
<!-- Jedis ConnectionFactory -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}"
p:port="${redis.port}" />
</beans>
操作Redis
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-data-redis.xml");
// 直接通过连接进行操作
JedisConnectionFactory jedisConnectionFactory = context.getBean(JedisConnectionFactory.class);
RedisConnection redisConnection = jedisConnectionFactory.getConnection();
// 设置值
redisConnection.set("name".getBytes(),"wangdh".getBytes());
// 获取值
byte[] value = redisConnection.get("name".getBytes());
System.out.println(new String(value));
}
示例说明
1. Spring Data Redis使用的是1.8.2.RELEASE,最新的2.x版本对配置进行了封装,并且基于Spring Cache的实现使用起来不习惯,就没选用2.x版本。
2. Spring Data Redis默认对数据进行了基于JDK的序列化,所以在redis中看到的数据是二进制类型数据,更改序列化方式即可。
3. 使用底层API:RedisConnection操作Redis,需要对数据进行手动转换(String byte),需要进行多数重复性工作,效率低下,下一节介绍更高层次的封装。
网友评论