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的工作原理