分布式緩存技術(shù)redis學(xué)習(xí)系列----深入理解Spring Redis的使用
關(guān)于spring redis框架的使用,網(wǎng)上的例子很多很多。但是在自己最近一段時(shí)間的使用中,發(fā)現(xiàn)這些教程都是入門教程,包括很多的使用方法,與spring redis豐富的api大相徑庭,真是浪費(fèi)了這么優(yōu)秀的一個(gè)框架。
Spring-data-redis為spring-data模塊中對redis的支持部分,簡稱為“SDR”,提供了基于jedis客戶端API的高度封裝以及與spring容器的整合,事實(shí)上jedis客戶端已經(jīng)足夠簡單和輕量級,而spring-data-redis反而具有“過度設(shè)計(jì)”的嫌疑。
jedis客戶端在編程實(shí)施方面存在如下不足:
1) connection管理缺乏自動化,connection-pool的設(shè)計(jì)缺少必要的容器支持。
2) 數(shù)據(jù)操作需要關(guān)注“序列化”/“反序列化”,因?yàn)閖edis的客戶端API接受的數(shù)據(jù)類型為string和byte,對結(jié)構(gòu)化數(shù)據(jù)(json,xml,pojo)操作需要額外的支持。
3) 事務(wù)操作純粹為硬編碼
4) pub/sub功能,缺乏必要的設(shè)計(jì)模式支持,對于開發(fā)者而言需要關(guān)注的太多。
1. Redis使用場景
Redis是一個(gè)開源的使用ANSI C語言編寫、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫,并提供多種語言的API。
我們都知道,在日常的應(yīng)用中,數(shù)據(jù)庫瓶頸是最容易出現(xiàn)的。數(shù)據(jù)量太大和頻繁的查詢,由于磁盤IO性能的局限性,導(dǎo)致項(xiàng)目的性能越來越低。
這時(shí)候,基于內(nèi)存的緩存框架,就能解決我們很多問題。例如Memcache,Redis等。將一些頻繁使用的數(shù)據(jù)放入緩存讀取,大大降低了數(shù)據(jù)庫的負(fù)擔(dān)。提升了系統(tǒng)的性能。其實(shí),對于hibernate以及Mybatis的二級緩存,是同樣的道理。利用內(nèi)存高速的讀寫速度,來解決硬盤的瓶頸。
2. 配置使用redis
項(xiàng)目的整體結(jié)構(gòu)如下:
在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的開發(fā)者而言,實(shí)在是非常便捷。sdr提供了4種內(nèi)置的serializer:
- JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable接口,ObjectInputStrean,ObjectOutputStream),數(shù)據(jù)以字節(jié)流存儲,POJO對象的存取場景,使用JDK本身序列化機(jī)制,將pojo類通過ObjectInputStream/ObjectOutputStream進(jìn)行序列化操作,最終redis-server中將存儲字節(jié)序列,是目前最常用的序列化策略。
- StringRedisSerializer:字符串編碼,數(shù)據(jù)以string存儲,Key或者value為字符串的場景,根據(jù)指定的charset對數(shù)據(jù)的字節(jié)序列編碼成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封裝。是最輕量級和高效的策略。
- JacksonJsonRedisSerializer:json格式存儲,jackson-json工具提供了javabean與json之間的轉(zhuǎn)換能力,可以將pojo實(shí)例序列化成json格式存儲在redis中,也可以將json格式的數(shù)據(jù)轉(zhuǎn)換成pojo實(shí)例。因?yàn)閖ackson工具在序列化和反序列化時(shí),需要明確指定Class類型,因此此策略封裝起來稍微復(fù)雜?!拘枰猨ackson-mapper-asl工具支持】
- OxmSerializer:xml格式存儲,提供了將javabean與xml之間的轉(zhuǎn)換能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存儲的數(shù)據(jù)將是xml工具。不過使用此策略,編程將會有些難度,而且效率***;不建議使用?!拘枰猻pring-oxm模塊的支持】
其中JdkSerializationRedisSerializer和StringRedisSerializer是最基礎(chǔ)的序列化策略,其中“JacksonJsonRedisSerializer”與“OxmSerializer”都是基于stirng存儲,因此它們是較為“高級”的序列化(最終還是使用string解析以及構(gòu)建java對象)。 針對“序列化和發(fā)序列化”中JdkSerializationRedisSerializer和StringRedisSerializer是最基礎(chǔ)的策略,原則上,我們可以將數(shù)據(jù)存儲為任何格式以便應(yīng)用程序存取和解析(其中應(yīng)用包括app,hadoop等其他工具),不過在設(shè)計(jì)時(shí)仍然不推薦直接使用“JacksonJsonRedisSerializer”和“OxmSerializer”,因?yàn)闊o論是json還是xml,他們本身仍然是String。如果你的數(shù)據(jù)需要被第三方工具解析,那么數(shù)據(jù)應(yīng)該使用StringRedisSerializer而不是JdkSerializationRedisSerializer。
RedisTemplate中需要聲明4種serializer,默認(rèn)為“JdkSerializationRedisSerializer”:
1) keySerializer :對于普通K-V操作時(shí),key采取的序列化策略
2) valueSerializer:value采取的序列化策略
3) hashKeySerializer: 在hash數(shù)據(jù)結(jié)構(gòu)中,hash-key的序列化策略
4) hashValueSerializer:hash-value的序列化策略
無論如何,建議key/hashKey采用StringRedisSerializer。
spring-data-redis針對jedis提供了如下功能:
1. 連接池自動管理,提供了一個(gè)高度封裝的“RedisTemplate”類
2. 針對jedis客戶端中大量api進(jìn)行了歸類封裝,將同一類型操作封裝為operation接口
- ValueOperations:簡單K-V操作
- SetOperations:set類型數(shù)據(jù)操作
- ZSetOperations:zset類型數(shù)據(jù)操作
- HashOperations:針對map類型的數(shù)據(jù)操作
- ListOperations:針對list類型的數(shù)據(jù)操作
3. 提供了對key的“bound”(綁定)便捷化操作API,可以通過bound封裝指定的key,然后進(jìn)行一系列的操作而無須“顯式”的再次指定Key,即BoundKeyOperations:
- BoundValueOperations
- BoundSetOperations
- BoundListOperations
- BoundSetOperations
- BoundHashOperations
3. RedisTemplate的使用
這個(gè)類作為一個(gè)模版類,提供了很多快速使用redis的api,而不需要自己來維護(hù)連接,事務(wù)。最初的時(shí)候,我創(chuàng)建的BaseRedisDao是繼承自這個(gè)類的。繼承的好處是我的每個(gè)Dao中,都可以自由的控制序列化器,自由的控制自己是否需要事務(wù),這個(gè)先不需要了解,跟著我目前的這種配置方法來即可。template提供了一系列的operation,比如valueOperation,HashOperation,ListOperation,SetOperation等,用來操作不同數(shù)據(jù)類型的Redis。并且,RedisTemplate還提供了對應(yīng)的*OperationsEditor,用來通過RedisTemplate直接注入對應(yīng)的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";
- }
- }