當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot高级-缓存-RedisTemplate序列化机制
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot高级-缓存-RedisTemplate序列化机制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前面我們就搭建測試好了redis環境,接下來我們就來整合redis來做緩存,我們需要引入redis的starter,這個starter我們直接去官方文檔去搜索就行了,我們來找到所有的starter跟redis有關的,這一塊有一個starters,https://docs.spring.io/spring-boot/docs/1.5.22.RELEASE/reference/html/using-boot-build-systems.html
#using-boot-starter在這里看redis,redis就是跟數據訪問的,數據訪問這里有非常多的starter,這里有一個spring-boot-starter-data-redisStarter for using Redis key-value data store with Spring Data Redis and the Jedis client我們就用它,我們先引入這個場景啟動器,我們在這引入<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>把它引入進來以后呢,我們redis相應的場景就引入進來了,他引入了哪些呢,點擊來,我們可以來看一下,這里主要引入了jedis客戶端<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId>
</dependency>接下來我們就來配置好redis,先用springboot測試,第三步配置redis,配置redis非常的簡單,我們只要指定spring.redis.host,指定一下redis的主機地址spring.redis.host=10.40.8.152就是這個地址,我們就來到這個測試類里面spring.redis.host=localhost # Redis server host.
spring.redis.password= # Login password of the redis server.
spring.redis.port=6379 # Redis server port.
當我們引入了redis場景以后,我們RedisAutoConfiguration,就不起作用了,由于我們引入了redis,@Configuration
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {包括有了Jedis,我們redis的自動配置就起效了,這個自動配置做了什么,我們來往下看,他給我們配了有兩個東西,@Bean給容器中加組件,* Standard Redis configuration.*/
@Configuration
protected static class RedisConfiguration {@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean(StringRedisTemplate.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}}加了一個RedisTemplate<Object, Object>,還有一個是StringRedisTemplate,相當于兩個RedisTemplate的東西,他就是用來操作redis的,就跟大家學的JdbcTemplate一樣,來操作數據庫的,這就是用來簡化操作redis的兩個template,我們把這兩個復制過來,如果要用,我們只需要自動注入就行了,還有一個就直接叫RedisTemplate,為什么會有兩個呢,RedisTemplate<Object, Object>兩個Object代表鍵值,鍵值都是對象的,由于我們經常跟連接字符串操作比較多,來專門操作字符串的,StringRedisTemplate,這個就是操作字符串的,redis操作的基本幾種類型,String(字符串),就和我們剛才在命令行操作的一樣,還有操作list,這個就是我們的列表,包括我們還操作過一個叫set,集合,包括里面還有一個常見的數據類型,hash,這是一個散列,包括還有一個叫Zset,這是一個有序集合,這是Redis常見的5大數據類型,這些template都能操作,我們先用StringRedisTemplate來演示,這里有一個方法,opsForValue,這個就是用來操作字符串的,。來簡化操作字符串的,stringRedisTemplate.opsForHash()操作我們Hash的,還有一個stringRedisTemplate.opsForList(),這是來操作列表的,這是來操作列表類型數據的,stringRedisTemplate.opsForSet()這個是來操作集合的,其他的不用講了,其實都是一樣,所以太會有對應的這幾個,我就把這些都復制過來了,這個template其實跟stringRedisTemplate一模一樣,他們都有這些操作,操作一些常用的數據,他跟他的不同我們以前說過,這些k-v都是對象的,我們用stringRedisTemplate來做一個例子,來操作字符串,操作字符串我們怎么操作,這里有append,相當于redis命令里邊,只要有這些命令,你基本上都能夠點出來,比如我們測試剛才的追加命令,比如我們的key就叫message,這個message的值就叫hello,剛才我們把redis數據庫給清空了,什么都沒有,我們相當于給redis中保存了一個數據,我們發現redis里msg hello也已經有了,我想把這個數據讀出來,讀我們就來寫一個get,我們要按照這個key來讀數據,append是追加字符串的,這里有一個set,給某一個key設置某一個值,我們發現有報錯,默認的序列化需要一個可序列化的類,但是我們Employee這個類是不可以序列化的,那我先把它給序列化一下,然后我再來運行,我們發現這里有數據,\xAC\xED\x00\x05t\x00\x06emp-01emp-01前面一大堆是什么呢,其實這都是序列化的結果,默認如果保存對象,使用jdk序列化機制,序列化的數據保存在redis里,我們還是習慣以json的方式保存,有兩種辦法,將數據以JSON的方式保存,我們自己 把數據轉換來,自己講對象轉為JSON,這種我們就不說了,大家都會轉,用市面上的JSON轉換工具,其實redisTemplate它有默認的序列化規則,RedisTemplate里邊,private RedisSerializer keySerializer = null;
private RedisSerializer valueSerializer = null;
private RedisSerializer hashKeySerializer = null;
private RedisSerializer hashValueSerializer = null;
private RedisSerializer<String> stringSerializer = new StringRedisSerializer();有keySerializer的序列化器,這些值的序列化器,我們來變一下規則就行了,@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();template.setConnectionFactory(redisConnectionFactory);return template;
}他就直接new了一個RedisTemplate,把redis的連接工廠放過來,把這個template返回,默認情況下我們看他的序列號器用的是什么,用的就是JdkSerializationRedisSerializerif (defaultSerializer == null) {defaultSerializer = new JdkSerializationRedisSerializer(classLoader != null ? classLoader : this.getClass().getClassLoader());
}我們來切換成JSON的序列號器引用我來寫一個MyRedisConfig,@Configuration,跟他的寫法是一樣的,我這里來放一個專門來序列化employee的,我們來放一個序列號器,只要我們導了JACKSON,我們就會有Jackson2JsonRedisSerializer,我們把它給拿過來,只不過他new的時候要傳入一個泛型,我們就是來轉換Employee的,這個是我們這個序列化器,讓我們這個template來使用這個序列化器,你都可以來寫相應的RedisTemplate,我們在測試類的時候就自動注入這個@Autowired
RedisTemplate<Object,Employee> empRedisTemplate;
package com.learn.entities;import java.io.Serializable;public class Employee implements Serializable {private Integer id;private String name;private String gender;private String title;private String email;private double salary;private Integer deptId;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public Integer getDeptId() {return deptId;}public void setDeptId(Integer deptId) {this.deptId = deptId;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Employee [id=" + id + ", name=" + name + ", gender=" + gender + ", title=" + title + ", email=" + email+ ", salary=" + salary + ", deptId=" + deptId + "]";}}
package com.learn.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import com.learn.entities.Employee;@Configuration
public class MyRedisConfig {@Beanpublic RedisTemplate<Object,Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory){RedisTemplate<Object,Employee> template = new RedisTemplate<Object,Employee>();template.setConnectionFactory(redisConnectionFactory);Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);template.setDefaultSerializer(ser);return template;}}
package com.learn.springboot;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;import com.learn.entities.Employee;
import com.learn.mapper.EmployeeMapper;/*** SpringBoot單元測試** 可以在測試期間很方便的類似編碼一樣進行自動注入等容器的功能*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot01CacheApplicationTests {// 操作k-v都是對象的@AutowiredStringRedisTemplate stringRedisTemplate;// 操作字符串的 k-v都是字符串的@AutowiredRedisTemplate<Object,Object> redisTemplate;@AutowiredEmployeeMapper employeeMapper;@AutowiredRedisTemplate<Object,Employee> empRedisTemplate;/*** Redis常見的五大數據類型* String(字符串),List(列表),Set(集合),Hash(散列),ZSet(有序集合)* stringRedisTemplate.opsForValue[String(字符串)]* stringRedisTemplate.opsForHash()[Hash(散列)]* stringRedisTemplate.opsForList()[List(列表)]* stringRedisTemplate.opsForSet()[Set(集合)]* stringRedisTemplate.opsForZSet()[ZSet(有序集合)]*/@Testpublic void test01() {// 給redis中保存一個數據
// stringRedisTemplate.opsForValue().append("msg", "hello");
// String msg = stringRedisTemplate.opsForValue().get("msg");
// System.out.println(msg);// stringRedisTemplate.opsForList().leftPush("mylist", "1");
// stringRedisTemplate.opsForList().leftPush("mylist", "2");}// 測試保存對象@Testpublic void test02() {Employee emp = employeeMapper.getEmpById(1);// 默認如果保存對象,使用jdk序列號機制,序列化后的數據保存到redis中
// redisTemplate.opsForValue().set("emp-01", emp);// 1.將數據以json的方式保存// (1)自己將對象轉為json// (2)redisTemplate默認的序列號規則empRedisTemplate.opsForValue().set("emp-01", emp);}
}
?
總結
以上是生活随笔為你收集整理的SpringBoot高级-缓存-RedisTemplate序列化机制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot高级-缓存-搭建re
- 下一篇: SpringBoot高级-消息-JMSA