分布式緩存技術redis學習系列----深入理解Spring Redis的使用
關于spring redis框架的使用,網上的例子很多很多。但是在自己最近一段時間的使用中,發現這些教程都是入門教程,包括很多的使用方法,與spring redis豐富的api大相徑庭,真是浪費了這么優秀的一個框架。
Spring-data-redis為spring-data模塊中對redis的支持部分,簡稱為“SDR”,提供了基于jedis客戶端API的高度封裝以及與spring容器的整合,事實上jedis客戶端已經足夠簡單和輕量級,而spring-data-redis反而具有“過度設計”的嫌疑。
jedis客戶端在編程實施方面存在如下不足:
1) connection管理缺乏自動化,connection-pool的設計缺少必要的容器支持。
2) 數據操作需要關注“序列化”/“反序列化”,因為jedis的客戶端API接受的數據類型為string和byte,對結構化數據(json,xml,pojo)操作需要額外的支持。
3) 事務操作純粹為硬編碼
4) pub/sub功能,缺乏必要的設計模式支持,對于開發者而言需要關注的太多。
1. Redis使用場景
Redis是一個開源的使用ANSI C語言編寫、支持網絡、可基于內存亦可持久化的日志型、Key-Value數據庫,并提供多種語言的API。
我們都知道,在日常的應用中,數據庫瓶頸是最容易出現的。數據量太大和頻繁的查詢,由于磁盤IO性能的局限性,導致項目的性能越來越低。
這時候,基于內存的緩存框架,就能解決我們很多問題。例如Memcache,Redis等。將一些頻繁使用的數據放入緩存讀取,大大降低了數據庫的負擔。提升了系統的性能。其實,對于hibernate以及Mybatis的二級緩存,是同樣的道理。利用內存高速的讀寫速度,來解決硬盤的瓶頸。
2. 配置使用redis
項目的整體結構如下:
在applicationContext-dao.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:context="http://www.springframework.org/schema/context"
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/data/mongo
- http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
- <context:property-placeholder location="classpath:database.properties" />
- <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
- <property name="maxIdle" value="${redis.maxIdle}" />
- <property name="maxTotal" value="${redis.maxActive}" />
- <property name="maxWaitMillis" value="${redis.maxWait}" />
- <property name="testOnBorrow" value="${redis.testOnBorrow}" />
- </bean>
- <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
- <property name="hostName" value="${redis.host}"/>
- <property name="port" value="${redis.port}"/>
- <property name="password" value="${redis.pass}"/>
- <property name="poolConfig" ref="poolConfig"/>
- </bean>
- <bean id="stringSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
- <bean id="hashSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
- <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
- <property name="connectionFactory" ref="connectionFactory" />
- <property name="keySerializer" ref="stringSerializer"/>
- <property name="valueSerializer" ref="stringSerializer"/>
- <property name="hashKeySerializer" ref="stringSerializer" />
- <property name="hashValueSerializer" ref="hashSerializer"/>
- </bean>
- </beans>
database.properties配置文件如下:
- redis.maxIdle=10
- redis.maxActive=20
- redis.maxWait=10000
- redis.testOnBorrow=true
- redis.host=192.168.1.76
- redis.port=6379
- redis.pass=password1
spring-data-redis提供了多種serializer策略,這對使用jedis的開發者而言,實在是非常便捷。sdr提供了4種內置的serializer:
- JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable接口,ObjectInputStrean,ObjectOutputStream),數據以字節流存儲,POJO對象的存取場景,使用JDK本身序列化機制,將pojo類通過ObjectInputStream/ObjectOutputStream進行序列化操作,最終redis-server中將存儲字節序列,是目前最常用的序列化策略。
- StringRedisSerializer:字符串編碼,數據以string存儲,Key或者value為字符串的場景,根據指定的charset對數據的字節序列編碼成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封裝。是最輕量級和高效的策略。
- JacksonJsonRedisSerializer:json格式存儲,jackson-json工具提供了javabean與json之間的轉換能力,可以將pojo實例序列化成json格式存儲在redis中,也可以將json格式的數據轉換成pojo實例。因為jackson工具在序列化和反序列化時,需要明確指定Class類型,因此此策略封裝起來稍微復雜。【需要jackson-mapper-asl工具支持】
- OxmSerializer:xml格式存儲,提供了將javabean與xml之間的轉換能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存儲的數據將是xml工具。不過使用此策略,編程將會有些難度,而且效率***;不建議使用。【需要spring-oxm模塊的支持】
其中JdkSerializationRedisSerializer和StringRedisSerializer是最基礎的序列化策略,其中“JacksonJsonRedisSerializer”與“OxmSerializer”都是基于stirng存儲,因此它們是較為“高級”的序列化(最終還是使用string解析以及構建java對象)。 針對“序列化和發序列化”中JdkSerializationRedisSerializer和StringRedisSerializer是最基礎的策略,原則上,我們可以將數據存儲為任何格式以便應用程序存取和解析(其中應用包括app,hadoop等其他工具),不過在設計時仍然不推薦直接使用“JacksonJsonRedisSerializer”和“OxmSerializer”,因為無論是json還是xml,他們本身仍然是String。如果你的數據需要被第三方工具解析,那么數據應該使用StringRedisSerializer而不是JdkSerializationRedisSerializer。
RedisTemplate中需要聲明4種serializer,默認為“JdkSerializationRedisSerializer”:
1) keySerializer :對于普通K-V操作時,key采取的序列化策略
2) valueSerializer:value采取的序列化策略
3) hashKeySerializer: 在hash數據結構中,hash-key的序列化策略
4) hashValueSerializer:hash-value的序列化策略
無論如何,建議key/hashKey采用StringRedisSerializer。
spring-data-redis針對jedis提供了如下功能:
1. 連接池自動管理,提供了一個高度封裝的“RedisTemplate”類
2. 針對jedis客戶端中大量api進行了歸類封裝,將同一類型操作封裝為operation接口
- ValueOperations:簡單K-V操作
- SetOperations:set類型數據操作
- ZSetOperations:zset類型數據操作
- HashOperations:針對map類型的數據操作
- ListOperations:針對list類型的數據操作
3. 提供了對key的“bound”(綁定)便捷化操作API,可以通過bound封裝指定的key,然后進行一系列的操作而無須“顯式”的再次指定Key,即BoundKeyOperations:
- BoundValueOperations
- BoundSetOperations
- BoundListOperations
- BoundSetOperations
- BoundHashOperations
3. RedisTemplate的使用
這個類作為一個模版類,提供了很多快速使用redis的api,而不需要自己來維護連接,事務。最初的時候,我創建的BaseRedisDao是繼承自這個類的。繼承的好處是我的每個Dao中,都可以自由的控制序列化器,自由的控制自己是否需要事務,這個先不需要了解,跟著我目前的這種配置方法來即可。template提供了一系列的operation,比如valueOperation,HashOperation,ListOperation,SetOperation等,用來操作不同數據類型的Redis。并且,RedisTemplate還提供了對應的*OperationsEditor,用來通過RedisTemplate直接注入對應的Operation。
核心代碼:
- package com.npf.dao.impl;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import javax.annotation.Resource;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.HashOperations;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.stereotype.Repository;
- import com.npf.dao.StudentDao;
- import com.npf.model.Student;
- @Repository
- public class StudentDaoImpl implements StudentDao{
- @Autowired
- private RedisTemplate<String,Student> redisTemplate;
- @Resource(name="redisTemplate")
- private HashOperations<String,String,Student> opsForHash;
- public static final String STUDENT = "student";
- @Override
- public void save(Student student) {
- opsForHash.put(STUDENT, student.getId(), student);
- }
- @Override
- public Student find(String id) {
- Student student = opsForHash.get(STUDENT, id);
- return student;
- }
- @Override
- public void delete(String id) {
- opsForHash.delete(STUDENT, id);
- }
- @Override
- public void update(Student student) {
- opsForHash.put(STUDENT, student.getId(), student);
- }
- @Override
- public List<Student> findAll() {
- Map<String, Student> entries = opsForHash.entries(STUDENT);
- List<Student> stuList = new ArrayList<Student>();
- for(Entry<String, Student> entry : entries.entrySet()){
- stuList.add(entry.getValue());
- }
- return stuList;
- }
- }
控制層代碼如下:
- package com.npf.controller;
- import java.util.List;
- import java.util.UUID;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import com.npf.model.Student;
- import com.npf.service.StudentService;
- @Controller
- public class StudentController {
- @Autowired
- private StudentService studentService;
- @RequestMapping("/student/save")
- public String saveStudent(Student student){
- String id = UUID.randomUUID().toString();
- System.out.println(id);
- student.setId(id);
- studentService.save(student);
- return "redirect:/student/find/all";
- }
- @RequestMapping("/student/update")
- public String updateStudent(Student student){
- studentService.update(student);
- return "redirect:/student/find/all";
- }
- @RequestMapping("/student/to/save/form")
- public String toSaveStudentForm(){
- return "save";
- }
- @RequestMapping("/student/delete")
- public String deleteStudent(@RequestParam("id") String id){
- studentService.delete(id);
- return "redirect:/student/find/all";
- }
- @RequestMapping("/student/to/update/form")
- public String toUpdateStudentForm(@RequestParam("id") String id,Model model){
- Student stu = studentService.find(id);
- model.addAttribute("stu", stu);
- return "update";
- }
- @RequestMapping("/student/find/all")
- public String findStudents(Model model){
- List<Student> stuList = studentService.findAll();
- model.addAttribute("stuList", stuList);
- return "list";
- }
- }