javascript
SpringBoot使用Redis和MyBatis完成缓存数据的增删改查
文章目錄
- 1.在Spring Boot中集成Redis
- 2.配置Redis類
- 關(guān)于Redis Template中序列化和反序列化配置的解釋
- 3.創(chuàng)建測(cè)試實(shí)體類
- 4.實(shí)現(xiàn)實(shí)體和數(shù)據(jù)表的映射關(guān)系
- 5.創(chuàng)建Redis緩存服務(wù)器
- 6.完成增刪改查測(cè)試API
- 7.啟動(dòng)測(cè)試
1.在Spring Boot中集成Redis
1)添加依賴
pom.xml
添加的依賴包含Redis,Mysql,MyBatis,fastjson,junit
2)配置application.properties
application.properties
配置mysql,redis服務(wù)器
3)在入口類加上@EnableCaching注解,開啟緩存支持
RedisDemoApplication.java
package com.example.demo;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication @EnableCaching public class RedisDemoApplication {public static void main(String[] args) {SpringApplication.run(RedisDemoApplication.class, args);}}4)建立下面的項(xiàng)目結(jié)構(gòu)
2.配置Redis類
要想啟動(dòng)Spring緩存支持,需要?jiǎng)?chuàng)建一個(gè)CacheManager的Bean。
RedisConfig.java
package com.example.demo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;import java.lang.reflect.Method;@Configurationpublic class RedisConfig extends CachingConfigurerSupport{@Beanpublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object target, Method method, Object... params) {StringBuilder sb = new StringBuilder();sb.append(target.getClass().getName());sb.append(method.getName());for (Object obj : params) {sb.append(obj.toString());}return sb.toString();}};}@SuppressWarnings("rawtypes")@Bean//緩存管理器public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory);//設(shè)置緩存過期時(shí)間return cacheManager;}@Beanpublic RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {//配置連接工廠StringRedisTemplate template = new StringRedisTemplate(factory);//使用Jackson2JsonRedisSerializer來序列化和反序列化redis 的value值Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();//指定要序列化的域,field,get和set,以及修飾符范圍om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);//om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);//指定序列化輸入的類型,類必須是非final類om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);jackson2JsonRedisSerializer.setObjectMapper(om);//序列化配置為String格式template.setValueSerializer(new StringRedisSerializer());//template.setKeySerializer(new StringRedisSerializer());template.afterPropertiesSet();return template;}}關(guān)于Redis Template中序列化和反序列化配置的解釋
關(guān)于數(shù)據(jù)的“序列化/反序列化”,提供了多種可選擇策略(RedisSerializer)
| JdkSerializationRedisSerializer | POJO對(duì)象的存取場(chǎng)景,使用JDK本身序列化機(jī)制,將pojo類通過ObjectInputStream/ObjectOutputStream進(jìn)行序列化操作,最終redis-server中將存儲(chǔ)字節(jié)序列。 |
| StringRedisSerializer | 適用于Key或者value為字符串的場(chǎng)景,根據(jù)指定的charset對(duì)數(shù)據(jù)的字節(jié)序列編碼成string |
| JacksonJsonRedisSerializer | 提供了javabean與json之間的轉(zhuǎn)換能力,可以將pojo實(shí)例序列化成json格式存儲(chǔ)在redis中,也可以將json格式的數(shù)據(jù)轉(zhuǎn)換成pojo實(shí)例。 |
| OxmSerializer | 提供了將javabean與xml之間的轉(zhuǎn)換能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存儲(chǔ)的數(shù)據(jù)將是xml工具。 |
上面4種策略中:
JdkSerializationRedisSerializer和StringRedisSerializer是最基礎(chǔ)的策略,在設(shè)計(jì)時(shí)仍然不推薦直接使用后面兩種,即JacksonJsonRedisSerializer和OxmSerializer,因?yàn)闊o論是json還是xml,他們本身仍然是String。
如果數(shù)據(jù)需要被第三方工具解析,那么數(shù)據(jù)應(yīng)該使用StringRedisSerializer而不是JdkSerializationRedisSerializer。
如果數(shù)據(jù)格式必須為json或者xml,那么在編程級(jí)別,在redisTemplate配置中仍然使用StringRedisSerializer,在存儲(chǔ)之前或者讀取之后,使用“SerializationUtils”工具轉(zhuǎn)換轉(zhuǎn)換成json或者xml
3.創(chuàng)建測(cè)試實(shí)體類
User.java
package com.example.demo.model;import lombok.Data;import java.io.Serializable;@Data public class User implements Serializable {private String id;private String name;private int age; }這里需要注意的是spring boot在啟動(dòng)時(shí)會(huì)自動(dòng)創(chuàng)建user表
在項(xiàng)目的resources目錄下新建db目錄,并添加schema.sql文件,寫入創(chuàng)建user表的sql語句
當(dāng)然還需要配置數(shù)據(jù)庫連接,并加上數(shù)據(jù)表初始化的配置(配置工作前面的文件中已經(jīng)包含)
這里是schema.sql
4.實(shí)現(xiàn)實(shí)體和數(shù)據(jù)表的映射關(guān)系
UserMapper.java
package com.example.demo.mapper;import com.example.demo.model.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository;@Repository @Mapper public interface UserMapper {@Insert("insert into user(name,age) values(#{name},#{age})")int addUser(@Param("name")String name,@Param("age")String age);@Select("select * from user where id=#{id}")User findById(@Param("id")String id);@Update("update user set name=#{name},age=#{age} where id=#{id}")int updateById(User user);@Delete("delete from user where id=#{id}")void deleteById(@Param("id")String id); }5.創(chuàng)建Redis緩存服務(wù)器
創(chuàng)建Redis緩存服務(wù)器,即緩存在服務(wù)器層面
UserService.java
代碼解釋
@Cacheable:將查詢結(jié)果緩存到Redis中
key="#p0":指定傳入的第一個(gè)參數(shù)作為Redis的key
@CachePut:指定key,將更新的結(jié)果同步到Redis中
@CacheEvict:指定key,刪除緩存數(shù)據(jù)
allEntries:方法調(diào)用后將立即清除緩存
6.完成增刪改查測(cè)試API
RedisController.java
package com.example.demo.controller; import com.example.demo.service.UserService; import com.example.demo.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController @RequestMapping("/user") public class RedisController {@AutowiredUserService userService;@RequestMapping("/{id}")public User ForTest(@PathVariable String id){return userService.selectUser(id);}@RequestMapping( "/update/")public String update(User user){userService.updateById(user);return "success";}@RequestMapping( "/delete/{id}")public String delete (@PathVariable String id){userService.deleteById(id);return "delete success";}}7.啟動(dòng)測(cè)試
1)啟動(dòng)Redis服務(wù)
由于沒有設(shè)置環(huán)境變量,需要手動(dòng)進(jìn)入到Redis安裝目錄cd /d D:\Redis-x64-3.2.100,然后啟動(dòng)服務(wù)
在cmd窗口打開的情況下,運(yùn)行項(xiàng)目
2)多次訪問
第一次時(shí)控制臺(tái)會(huì)出現(xiàn)select信息,代表對(duì)數(shù)據(jù)庫進(jìn)行了查詢操作。后面再訪問則不會(huì)出現(xiàn)提示,表示沒有對(duì)數(shù)據(jù)庫執(zhí)行操作,而是使用Redis中的緩存數(shù)據(jù)。
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的SpringBoot使用Redis和MyBatis完成缓存数据的增删改查的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA一直卡在Resolving Ma
- 下一篇: JavaScript响应键盘不再用Key