Using the underlying API: RedisConnectionFactory
and RedisConnection
You can manipulate Redis directly, here's a simple example:
# # Maven Dependency
<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>
Configure Redis.properties
redis.host=127.0.0.1redis.port=6379
Configure 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/beanshttp://www.springframework.org/schema/beans/ Spring-beans.xsd "><!--reading the properties file--><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= "I Gnoreresourcenotfound "value=" true "/> <property name=" Ignoreunresolvableplaceholders "value=" true "/> <p Roperty 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>
Operating 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));}
Example description
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),需要进行多数重复性工作,效率低下,下一节介绍更高层次的封装。
Spring Data Redis Primer Example: based on Jedis and underlying API (II)