當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Springboot+Redis+MybatisPlus实现页面缓存增删改查
生活随笔
收集整理的這篇文章主要介紹了
Springboot+Redis+MybatisPlus实现页面缓存增删改查
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.導入依賴
本章需要特別導入的依賴
<!-- 添加jedis依賴 --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.0.1</version></dependency><!-- redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>全文依賴
<dependencies><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.15</version></dependency><!--Velocity(默認--><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.2</version></dependency><!--swagger--><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version></dependency><!-- 添加jedis依賴 --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.0.1</version></dependency><!-- redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>2.yml文件配置
spring:datasource:druid:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/goodsusername: rootpassword: sasa#配置redisredis:#設置數據庫0-15database: 0#主機號host: 127.0.0.1#端口號port: 6379jedis:pool:max-wait: 1000msmax-active: 8max-idle: 8min-idle: 5mvc:pathmatch:matching-strategy: ant_path_matcher #mp日志報錯 mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl3.數據庫展示
?4.包展示
5. HTML頁面展示
1.首頁頁面
?
?
?redis緩存數據
?
?2.新增頁面
?
?因為我這里用的是批量新增,所有新增了三條數據
redis緩存數據
3.刪除頁面
這里我們刪除最后一條冰紅茶的數據,就只有兩條冰紅茶數據了
?
?
?redis緩存數據
4.修改頁面
我們把最后一條冰紅茶數據修改成可樂
?
?
?redis緩存數據
6.HTML代碼實現?
總共用到了三個頁面
?list.html頁面代碼實現
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script> </head> <body> <div style="text-align: center"><table style="margin: 0px auto"><tr><td>商品編號</td><td>商品名字</td><td>商品價格</td><td>庫存</td><td>所屬類型</td><td>操作</td></tr><tr th:each="list:${page}"><td th:text="${list.id}" id="id"></td><td th:text="${list.name}"></td><td th:text="${list.price}"></td><td th:text="${list.count}"></td><td th:text="${list.type}"></td><td><input type="button" onclick="location.href='/goods/toInsert'" th:value="新增"></td><td><input th:type="button" th:value ="刪除" th:onclick="dele([[${list.id}]])" ></td><td><a th:href="'/goods/toUpdate/'+${list.id}">修改</a></td></tr><tr align="center"></tr></table> </div> </body> <script>function dele(a) {$.ajax({url:'/goods/delete/'+a,type:'delete',dataType:'json',success:function (bool){if (bool==true)alert("刪除成功")location.href="/goods/list"if (bool==false)alert("刪除失敗")},contentType: 'application/json;charset=UTF-8'})} </script> </html>insert.html頁面代碼實現
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script> </head> <body> 商品名稱<input type="text" id="name" > 商品價格<input type="text" id="price" > 庫存<input type="text" id="count" > 商品類型<input type="text" id="type" > <input type="button" value="新增" onclick="insert()"> </body> <script>function insert() {var name=$("#name").val()var price=$("#price").val()var count=$("#count").val()var type=$("#type").val()var a={'name':name,'price':price,'count':count,'type':type}$.ajax({url:'/goods/save',type:'post',dataType:'json',data:JSON.stringify(a),success:function (data){if (data==true) {alert("新增成功")location.href="/goods/list"}},contentType: 'application/json;charset=UTF-8'})}</script> </html>update.html頁面代碼實現
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script> </head> <body> <!--<input type="text" th:value="${allGoodsById.id}" id="id" hidden>--> <!--商品名稱<input type="text" th:value="${allGoodsById.name}" id="name">--> <!--商品價格<input type="text" th:value="${allGoodsById.price}" id="price">--> <!--庫存<input type="text" th:value="${allGoodsById.count}" id="count">--> <!--所屬類型<input type="text" th:value="${allGoodsById.type}" id="type"><br>--> <!--<input type="button" onclick="update()" value="修改">--> <input type="text" id="id" th:value="${allGoodsById.id}" hidden> 商品名稱<input type="text" id="name"> 商品價格<input type="text" id="price"> 庫存<input type="text" id="count"> 所屬類型<input type="text" id="type"><br> <input type="button" onclick="update()" value="修改"> </body> <script>function update() {var id=$("#id").val()var name=$("#name").val()var price=$("#price").val()var count=$("#count").val()var type=$("#type").val()var data={'id':id,'name':name,'price':price,'count':count,'type':type}$.ajax({url:'/goods/update',type:'post',data:JSON.stringify(data),dataType:'json',success:function (bool){if (bool==true){alert("修改成功!")location.href="/goods/list"}if (data==false){alert("修改失敗!")}},contentType: 'application/json;charset=UTF-8'})} </script> </html>7.controller層代碼實現
package com.xcj.controller; import com.xcj.pojo.Goods; import com.xcj.service.GoodsService; import com.xcj.utils.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import redis.clients.jedis.Jedis; import java.util.List;@Controller @RequestMapping("/goods") public class GoodsController {@Autowiredprivate GoodsService goodsService;@RequestMapping("/list")public String getAllGoodes(Model model, JsonUtils jsonUtils, Jedis jedis){Object sel = goodsService.sel(jsonUtils, jedis);List<Goods> ts =jsonUtils.jsonToList((String) sel,Goods.class);model.addAttribute("page",ts);return "list";}//跳轉新增頁面@RequestMapping("/toInsert")public String toInsert(){return "insert";}//新增商品@ResponseBody@PostMapping("/save")public boolean save(Jedis jedis,@RequestBody Goods goods){return goodsService.saves(goods,jedis);}//根據id刪除商品@ResponseBody@DeleteMapping("/delete/{id}")public boolean toDelete(@PathVariable("id")Integer id,Jedis jedis){return goodsService.removeId(id,jedis);}//跳轉修改頁面@RequestMapping("/toUpdate/{id}")public String toUpdate(@PathVariable("id")Integer id,Model model){Goods allGoodsById = goodsService.getById(id);model.addAttribute("allGoodsById",allGoodsById);return "update";}//修改數據@RequestMapping(value = "/update",method = RequestMethod.POST)@ResponseBodypublic boolean update(@RequestBody Goods goods, Jedis jedis){return goodsService.Update(goods,jedis);}}?8.實體類代碼實現
?這里用的是MybatisX自動生成實體類
package com.xcj.pojo;import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import lombok.Data;/*** * @TableName goods*/ @TableName(value ="goods") @Data public class Goods implements Serializable {/*** */@TableId(type = IdType.AUTO)private Integer id;/*** */private String name;/*** */private Integer price;/*** */private Integer count;/*** */private Integer type;@TableField(exist = false)private static final long serialVersionUID = 1L;@Overridepublic boolean equals(Object that) {if (this == that) {return true;}if (that == null) {return false;}if (getClass() != that.getClass()) {return false;}Goods other = (Goods) that;return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))&& (this.getPrice() == null ? other.getPrice() == null : this.getPrice().equals(other.getPrice()))&& (this.getCount() == null ? other.getCount() == null : this.getCount().equals(other.getCount()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()));}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((getId() == null) ? 0 : getId().hashCode());result = prime * result + ((getName() == null) ? 0 : getName().hashCode());result = prime * result + ((getPrice() == null) ? 0 : getPrice().hashCode());result = prime * result + ((getCount() == null) ? 0 : getCount().hashCode());result = prime * result + ((getType() == null) ? 0 : getType().hashCode());return result;}@Overridepublic String toString() {StringBuilder sb = new StringBuilder();sb.append(getClass().getSimpleName());sb.append(" [");sb.append("Hash = ").append(hashCode());sb.append(", id=").append(id);sb.append(", name=").append(name);sb.append(", price=").append(price);sb.append(", count=").append(count);sb.append(", type=").append(type);sb.append(", serialVersionUID=").append(serialVersionUID);sb.append("]");return sb.toString();} }9.工具類代碼實現
package com.xcj.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Component;import java.util.List;@Component public class JsonUtils {// 定義jackson對象private static final ObjectMapper MAPPER = new ObjectMapper();/*** 將對象轉換成json字符串。* <p>Title: pojoToJson</p>* <p>Description: </p>* @param data* @return*/public static String objectToJson(Object data) {try {String string = MAPPER.writeValueAsString(data);return string;} catch (JsonProcessingException e) {e.printStackTrace();}return null;}/*** 將json結果集轉化為對象** @param jsonData json數據* @param class 對象中的object類型* @return*/public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {try {T t = MAPPER.readValue(jsonData, beanType);return t;} catch (Exception e) {e.printStackTrace();}return null;}/*** 將json數據轉換成pojo對象list* <p>Title: jsonToList</p>* <p>Description: </p>* @param jsonData* @param beanType* @return*/public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);try {List<T> list = MAPPER.readValue(jsonData, javaType);return list;} catch (Exception e) {e.printStackTrace();}return null;}}10.service層代碼實現
GoodsService
package com.xcj.service;import com.xcj.pojo.Goods; import com.baomidou.mybatisplus.extension.service.IService; import com.xcj.utils.JsonUtils; import redis.clients.jedis.Jedis;import java.util.List;/** * @author 24371 * @description 針對表【goods】的數據庫操作Service * @createDate 2022-11-28 18:24:20 */ public interface GoodsService extends IService<Goods> {/*** redis緩存查詢數據* @return object* */Object sel(JsonUtils jsonUtils, Jedis jedis);/*** redis刪除緩存數據* @return boolean* */boolean removeId(Integer id,Jedis jedis);/*** redis新增緩存數據* @return boolean* */boolean saves(Goods goods, Jedis jedis);/*** redis修改緩存數據* @return boolean* */boolean Update(Goods goods, Jedis jedis); }?GoodsServiceImpl
package com.xcj.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xcj.config.JedisDao; import com.xcj.pojo.Goods; import com.xcj.service.GoodsService; import com.xcj.mapper.GoodsMapper; import com.xcj.utils.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis;import java.util.ArrayList; import java.util.List;/** * @author 24371 * @description 針對表【goods】的數據庫操作Service實現 * @createDate 2022-11-28 18:24:20 */ @Service public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods>implements GoodsService{@Autowiredprivate GoodsMapper goodsMapper;@Overridepublic Object sel(JsonUtils jsonUtils, Jedis jedis) {//從redis緩存中獲取goods,獲取到了直接返回if (jedis.get("goods") != null) {String s = jedis.get("goods");return s;} else {//沒獲取到的話進入到mysql查詢到了數據再返回List<Goods> goods = goodsMapper.selectList(null);jedis.set("goods", jsonUtils.objectToJson(goods));String s = jedis.get("goods");return s;}}@Overridepublic boolean removeId(Integer id, Jedis jedis) {//如果有數據可刪除if (goodsMapper.deleteById(id) > 0) {//刪除redis緩存數據jedis.del("goods");//刪除mysql中數據goodsMapper.deleteById(id);return true;}return false;}@Overridepublic boolean saves(Goods goods, Jedis jedis) {List<Goods> list = new ArrayList<>();for (int i = 0; i < 3; i++) {list.add(goods);}if (list != null) {//MybatisPlus批量新增saveBatch(list);//刷新redis庫jedis.flushDB();return true;}return false;}@Overridepublic boolean Update(Goods goods, Jedis jedis) {if (goods != null) {//修改數據saveOrUpdate(goods);//刷新redis庫jedis.flushDB();return true;}return false;} }總結
以上是生活随笔為你收集整理的Springboot+Redis+MybatisPlus实现页面缓存增删改查的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的IT之路,在哪里?
- 下一篇: SpringBoot集成Redis和配置