1. SpringBoot整合Redis
1.1 切換開發環境
1.1.1 資料源配置

1.1.2 修改properties組態檔
說明:修改圖片配置路徑的檔案 image.properties檔案.
#properties的作用就是封裝key=value 業務資料
image.dirPath=D:/JT-SOFT/images
#image.dirPath=/usr/local/src/images
image.urlPath=http://image.jt.com
1.1.3 修改hosts檔案

1.1.4 修改nginx配置

1.2 整合Redis
1.2.1 引入jar包
<!--spring整合redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
1.2.2 入門測驗案例
package com.jt.test;
import com.baomidou.mybatisplus.annotation.TableId;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.params.SetParams;
//@SpringBootTest //如果需要在測驗類中引入spring容器機制才使用該注解
public class TestRedis {
/**
* 測驗遠程redis服務器是否可用
* host: 192.168.126.129
* port: 6379
* 思路:
* 1.實體化鏈接物件
* 2.利用物件執行redis命令
*
* 報錯除錯:
* 1.檢查Redis.conf的組態檔是否按照要求修改 ip/保護/后臺
* 2.redis啟動方式 redis-server redis.conf
* 3.關閉防火墻 systemctl stop firewalld.service
* */
@Test
public void test01(){
Jedis jedis = new Jedis("192.168.126.129",6379);
jedis.set("redis", "測驗redis是否可用");
System.out.println(jedis.get("redis"));
}
/**
* String型別API學習
* 需求: 判斷key是否存在于Redis.如果存在則不賦值,否則入庫.
*
*/
@Test
public void test02(){
Jedis jedis = new Jedis("192.168.126.129",6379);
if(jedis.exists("redis")){
System.out.println("資料已存在");
jedis.expire("redis", 10);
}else{
jedis.set("redis", "aaaa");
}
System.out.println(jedis.get("redis"));
}
//可以利用優化的API實作業務功能.
//業務: 如果資料存在則不賦值
@Test
public void test03(){
Jedis jedis = new Jedis("192.168.126.129",6379);
jedis.flushAll(); //清空redis服務器
// 如果key存在則不做任何操作
jedis.setnx("redis", "測驗賦值操作!!!");
System.out.println(jedis.get("redis"));
}
/**
* 測驗添加超市時間的有效性.
* 業務: 向redis中保存一個資料之后,要求設定10秒有效.
* 原子性: 要么同時成功,要么同時失敗.
*/
@Test
public void test04(){
Jedis jedis = new Jedis("192.168.126.129",6379);
/* jedis.set("aa", "aa"); //該資料將永不洗掉.
int a = 1/0;
jedis.expire("aa", 10);*/
jedis.setex("aa", 10, "aa"); //單位秒
//jedis.psetex(, ); //設定毫秒
}
/**
* 需求: 要求添加一個資料,只有資料存在時才會賦值,并且需要添加超時時間
* 保證原子性操作.
* private static final String XX = "xx"; 有key的時候才賦值
* private static final String NX = "nx"; 沒有key時才賦值
* private static final String PX = "px"; 毫秒
* private static final String EX = "ex"; 秒
* redis分布式鎖的問題
* */
@Test
public void test05(){
Jedis jedis = new Jedis("192.168.126.129",6379);
SetParams setParams = new SetParams();
setParams.xx().ex(10);
jedis.set("aaa", "aaa", setParams);
}
@Test
public void testList(){
Jedis jedis = new Jedis("192.168.126.129",6379);
jedis.lpush("list2", "1,2,3,4,5");
System.out.println(jedis.rpop("list2"));
}
/**
* 控制redis事務
* 說明:操作redisredis適用于事務控制
* 但是如果是多臺redis則不太適用事務.
* */
@Test
public void testTx(){
Jedis jedis = new Jedis("192.168.126.129",6379);
//開啟事務
Transaction transaction = jedis.multi();
try {
transaction.set("bb", "bb");
transaction.exec(); //提交事務
}catch (Exception e){
transaction.discard();
}
}
}
1.3 SpringBoot整合Redis
1.3.1 配置類的位置說明
說明:由于redis之后會被其他的服務器適用,所以最好的方式將Redis的配置類保存到common中.
1.3.2 編輯Pro檔案類

1.3.3 編輯配置類
package com.jt.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.Jedis;
@Configuration //標識我是一個配置類
@PropertySource("classpath:/properties/redis.properties")
public class JedisConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private Integer port;
/**
* 將jedis物件交給spring容器管理
*/
@Bean
public Jedis jedis(){
//由于將代碼寫死不利于擴展,所以將固定的配置添加到組態檔中
return new Jedis(host,port);
}
}
1.4 物件與JSON之間轉化
1.4.1 物件轉化為JSON
package com.jt.test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.pojo.ItemDesc;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ObjectMapperTest {
//實作物件與JSON之間的轉化
//任務: 物件轉化為json
@Test
public void test01(){
ObjectMapper objectMapper = new ObjectMapper();
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc("json測驗")
.setCreated(new Date()).setUpdated(new Date());
try {
//1.將物件轉化為json
String result = objectMapper.writeValueAsString(itemDesc);
System.out.println(result);
//2.將json資料轉化為物件 只能通過反射機制..
//給定xxx.class型別 之后實體化物件.利用物件的get/set方法為屬性賦值.
ItemDesc itemDesc2 = objectMapper.readValue(result,ItemDesc.class);
System.out.println(itemDesc2.toString());
System.out.println(itemDesc2.getCreated());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Test
public void test02(){
ObjectMapper objectMapper = new ObjectMapper();
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc("json測驗")
.setCreated(new Date()).setUpdated(new Date());
List<ItemDesc> list = new ArrayList<>();
list.add(itemDesc);
list.add(itemDesc);
//1.將物件轉化為JSON
try {
String json = objectMapper.writeValueAsString(list);
System.out.println(json);
//2.json轉化為物件
List<ItemDesc> list2 = objectMapper.readValue(json, list.getClass());
System.out.println(list2);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
1.5 封裝ObjectMapperUtil
1.5.1 業務說明
為了降低工具API ObjectMapper中的例外處理,需要準備一些工具API簡化代碼的呼叫.
方法1: 將任意的物件轉化為JSON.
方法2: 將任意的JSON串轉化為物件.
要求完成例外的處理.
1.5.2 定義工具API
說明:在jt-common中添加工具API物件
package com.jt.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
public class ObjectMapperUtil {
//定義常量物件
// 優勢1: 物件獨一份節省空間
// 優勢2: 物件不允許別人隨意篡改
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 1.將任意物件轉化為JSON
* 思考1: 任意物件物件應該使用Object物件來接
* 思考2: 回傳值是JSON串 所以應該是String
* 思考3: 使用什么方式轉化JSON FASTJSON/objectMapper
*/
public static String toJSON(Object object){
try {
if(object == null){
throw new RuntimeException("傳遞的引數object為null,請認真檢查");
}
return MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
//應該將檢查例外,轉化為運行時例外.
throw new RuntimeException("傳遞的物件不支持json轉化/檢查是否有get/set方法");
}
}
//2.將任意的JSON串轉化為物件 傳遞什么型別轉化什么物件
public static <T> T toObject(String json,Class<T> target){
if(StringUtils.isEmpty(json) || target == null){
throw new RuntimeException("傳遞的引數不能為null");
}
try {
return MAPPER.readValue(json,target);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException("json轉化例外");
}
}
}
1.5.3 測驗工具API是否可用
@Test
public void test03(){
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc("json測驗")
.setCreated(new Date()).setUpdated(new Date());
String json = ObjectMapperUtil.toJSON(itemDesc);
ItemDesc itemDesc2 =
ObjectMapperUtil.toObject(json, ItemDesc.class);
System.out.println(json);
System.out.println(itemDesc2);
}
1.6 實作商品分類的快取
1.6.1 編輯ItemCatController
/**
* 關于快取實作業務說明
* 1.應該查詢快取
* 2.判斷快取中是否有資料
* 3.如果沒有數據,則查詢資料庫
* 4.如果有資料,則直接回傳資料.
*
* 思考: redis中主要操作的型別是String型別,業務資料如何于String進行互動!!!!!
* 實作思路: 業務資料 ~~~ JSON ~~~ String
* @param id
* @return
*/
@RequestMapping("/list")
public List<EasyUITree> findItemCatList(Long id){
//當初始時樹形結構沒有加載不會傳遞ID,所以ID為null.只需要傳遞0.
Long parentId = (id==null)?0:id;
//return itemCatService.findItemCatList(parentId);
return itemCatService.findItemCache(parentId);
}
1.6.2 編輯ItemCatService
/**
* 步驟:
* 先查詢Redis快取 K:V
* true 直接回傳資料
* false 查詢資料庫
*
* KEY有什么特點: 1.key應該動態變化 2.key應該標識業務屬性
* key=ITEM_CAT_PARENTID::parentId
* @param parentId
* @return
*/
@Override
public List<EasyUITree> findItemCache(Long parentId) {
//0.定義空集合
List<EasyUITree> treeList = new ArrayList<>();
String key = "ITEM_CAT_PARENTID::"+parentId;
//1.從快取中查詢資料
String json = jedis.get(key);
//2.校驗JSON中是否有值.
if(StringUtils.isEmpty(json)){
//3.如果快取中沒有資料,則查詢資料庫
treeList = findItemCatList(parentId);
//4.為了實作快取處理應該將資料添加到redis中.
//將資料轉化為json結構,保存到redis中
json = ObjectMapperUtil.toJSON(treeList);
jedis.set(key, json);
System.out.println("第一次查詢資料庫!!!!");
}else{
//標識程式有值 將json資料轉化為物件即可
treeList =
ObjectMapperUtil.toObject(json,treeList.getClass());
System.out.println("查詢Redis快取服務器成功!!!!");
}
return treeList;
}
1.6.3 Redis速度測驗

作業
- 完成Redis案例測驗
- 將Redis命令了解 官網命令 Set/zSet
- AOP優化快取.
1.利用自定義的注解 @CacheFind 標識快取業務.(博客)
2.了解通知的型別
3.了解切入點運算式
4.復習AOP的作業原理
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/12908.html
標籤:其他
上一篇:【redis6.0.6】redis原始碼慢慢學,慢慢看 -- 第五天:adlist
下一篇:9-9華為筆試,3題AK
