說明:請注意Spring Data Redis的版本以及Spring的版本!最新版本的Spring Data Redis已經去除Jedis的依賴包,需要自行引入,這個是個坑點。並且會與一些低版本的Spring有沖突,要看官方文檔和不斷的測試。
Jedis是一款Java連接Redis的客戶端,Spring基於Jedis進行了封裝,提供了簡潔的操作Redis的方法。那就是Spring Data Redis。其實后來研究發現,Spring Data Redis集成不止Jedits這一款,還有很多款,這些都可以通過注入連接工廠來去指定。
要使用Spring Data Redis需要做如下步驟的操作思路:
1、先建立連接工廠,這個連接工廠是用來設置IP,端口,賬號密碼等。
2、通過連接工廠建立Session。
3、然后在代碼上注入Session進行使用。
實現步驟:
1、POM
<!-- Redis --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.11.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.2</version> </dependency>
2、JedisConnectionFactory建立Redis連接工廠
類似於數據庫連接池一樣,Redis客戶端也建立一個連接工廠
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory connFactory = new JedisConnectionFactory(); connFactory.setHostName("127.0.0.1"); connFactory.setPort(6379); connFactory.setUsePool(true);//使用連接池 return connFactory; }
4、Redis的RedisTemplate
有了Redis連接工廠,就要具體的Redis Session了。
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; @Bean public RedisTemplate<String, String> redis() { RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); redisTemplate.setConnectionFactory(jedisConnectionFactory()); redisTemplate.setKeySerializer(new StringRedisSerializer());//key的序列化適配器 redisTemplate.setValueSerializer(new StringRedisSerializer());//value的序列化適配器,也可以自己編寫,大部分場景StringRedisSerializer足以滿足需求了。 return redisTemplate; }
4、操作Redis
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; @Component public class CacheDemo { @Autowired
private RedisTemplate<String, String> redis; public void set(String key,String value){ redis.opsForValue().set(key, value); } }
redis.opsForValue():封裝操作String
redis.opsForList():封裝操作List
redis.opsForSet():封裝操作Set
redis.opsForZSet():封裝操作Sorted Set
redis.opsForHash():封裝操作Hash
6、基於XML的配置
上面是基於注解的方式注入連接工廠和Session的,如果是基於XML的配置,可以這樣設置。
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis1.host}" /> <property name="port" value="${redis1.port}" /> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> </bean> <bean id="redisOps" class="com.xjj.spring.data.XjjStringRedisOps"> <property name="connectionFactory" ref="jedisConnectionFactory" /> </bean>
說明:XjjStringRedisOps是自己封裝的Session
參考:
http://haoran-10.iteye.com/blog/2261703(以上內容轉自此篇文章,觀察最后一句話,貌似這個博主有些心事!)
http://www.itkeyword.com/doc/240592287730467262/redis-spring-data-jedisjavajunit