日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot使用Redis和MyBatis完成缓存数据的增删改查

發(fā)布時(shí)間:2025/4/5 javascript 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot使用Redis和MyBatis完成缓存数据的增删改查 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

      • 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

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>

2)配置application.properties

application.properties
配置mysql,redis服務(wù)器

spring.datasource.url=jdbc:mysql://127.0.0.1/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql= truespring.datasource.initialization-mode=always spring.datasource.schema=classpath:db/schema.sql# Redis數(shù)據(jù)庫索引(默認(rèn)為0) spring.redis.database=1 # Redis服務(wù)器地址 spring.redis.host=127.0.0.1 # Redis服務(wù)器連接端口 spring.redis.port=6379 # Redis服務(wù)器連接密碼(默認(rèn)為空) spring.redis.password=# 連接池最大連接數(shù)(使用負(fù)值表示沒有限制) spring.redis.jedis.pool.max-active=8# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒有限制) spring.redis.jedis.pool.max-wait=-1# 連接池中的最大空閑連接 spring.redis.jedis.pool.max-idle=8# 連接池中的最小空閑連接 spring.redis.jedis.pool.min-idle=0# 連接超時(shí)時(shí)間(毫秒) spring.redis.timeout=5000

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)

序列化/發(fā)序列化解釋
JdkSerializationRedisSerializerPOJO對(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

DROP TABLE IF EXISTS user; --IF object_id('user','U') is not NULL drop table 'user'; CREATE TABLE user(id int(11) NOT NULL AUTO_INCREMENT,name varchar(255) DEFAULT NULL,age int(11) DEFAULT NULL,PRIMARY KEY (id) )ENGINE=InnoDB DEFAULT CHARSET=utf8;

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)用后將立即清除緩存

package com.example.demo.service;import com.example.demo.model.User; import com.example.demo.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service;//Redis緩存服務(wù)層 @Service @CacheConfig(cacheNames = "users") public class UserService {@AutowiredUserMapper userMapper;@Cacheable(key="#p0")public User selectUser(String id){System.out.println("select");return userMapper.findById(id);}@CachePut(key="#p0")public void updateById(User user){System.out.println("uddate");userMapper.updateById(user);}//如果allEntries指定為true,則調(diào)用CacheEvict方法后將立即清空所有緩存@CacheEvict(key="#p0",allEntries = true)public void deleteById(String id){System.out.println("delete");userMapper.deleteById(id);} }

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ù)

redis-server.exe redis.windows.conf

在cmd窗口打開的情況下,運(yùn)行項(xiàng)目

2)多次訪問

http://localhost:8080/user/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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。