1 切换开发环境

1.1 数据源配置

springboot将对象转为XML springboot转json_springboot将对象转为XML

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.3 修改hosts文件

springboot将对象转为XML springboot转json_json_02

1.4 修改nginx配置

springboot将对象转为XML springboot转json_数据_03

2 整合Redis

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>

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();
        }
    }

}

3 SpringBoot整合Redis

3.1 配置类的位置说明

说明:由于redis之后会被其他的服务器适用,所以最好的方式将Redis的配置类保存到common中.

3.2 编辑Pro文件类

springboot将对象转为XML springboot转json_数据_04

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);
    }
}

4 对象与JSON之间转化

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();
        }
    }
}

5 封装ObjectMapperUtil

5.1 业务说明

为了降低工具API ObjectMapper中的异常处理,需要准备一些工具API简化代码的调用.
方法1: 将任意的对象转化为JSON.
方法2: 将任意的JSON串转化为对象.
要求完成异常的处理.

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转化异常");
        }
    }
}

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);
    }

6 实现商品分类的缓存

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);
    }

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;
    }

6.3 Redis速度测试

springboot将对象转为XML springboot转json_springboot将对象转为XML_05

1 AOP实现Redis缓存服务

1.1 现有代码的分析

说明:
1.虽然在业务层service中完成了代码的实现.但是该代码不具有复用性.如果换了其他的业务则需要重新编辑.
2.由于缓存的代码写在业务层service中,所以代码的耦合性高,不方便以后的扩展.
需求:
1.能否实现代码的复用.
2.能否降低代码的耦合性.

1.2 AOP

1.2.1 AOP作用

名称:面向切面编程.
一句话总结: 在不改变原有代码的条件下,对功能进行扩展.
公式: AOP = 切入点表达式 + 通知方法.

专业术语:
1.连接点: 在执行正常的业务过程中满足了切入点表达式时进入切面的点.(织入) 多个
2.通知: 在切面中执行的具体的业务(扩展) 方法
3.切入点: 能够进入切面的一个判断 if判断 一个
4.目标方法: 将要执行的真实的业务逻辑.

1.2.2 关于通知说明

1.前置通知: 目标方法执行之前执行
2.后置通知: 目标方法执行之后执行
3.异常通知: 目标方法执行之后抛出异常时执行
4.最终通知: 不管什么时候都要执行的方法.
说明:上述的四大通知类型不能控制目标方法是否执行.一般使用上述的四大通知类型,都是用来记录程序的执行状态.

5.环绕通知: 在目标方法执行前后都要执行的通知方法. 控制目标方法是否执行.并且环绕通知的功能最为强大.

1.2.3 切入点表达式说明

1). bean(bean的id) 类名首字母小写 匹配1个类
2). within(包名.类名) 按包路径匹配类 匹配多个类
上述表达式是粗粒度的控制,按类匹配.
3).execution(返回值类型 包名.类名.方法名(参数列表))
4).@annotation(包名.注解名) 按注解进行拦截.

1.2.4 AOPDemo复习

package com.jt.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component  //将对象交给spring容器管理
@Aspect     //标识我是一个切面
public class CacheAOP {

    /**
     * AOP = 切入点表达式 + 通知方法.
     *
     * 拦截需求:
     *  1.要求拦截itemCatServiceImpl的bean
     *  2.拦截com.jt.service下的所有的类
     *  3.拦截com.jt.service下的所有类及方法
     *  3.1拦截com.jt.service的所有的类.返回值为int类型的.并且add开头
     *  的方法.并且参数一个 为String类型
     */
    //@Pointcut(value = "bean(itemCatServiceImpl)")
    //@Pointcut("within(com.jt.service..*)")
    //拦截com.jt.service下的所有类的所有方法的任意参数类型
    //@Pointcut("execution(int com.jt.service..*.add*(String))")
    @Pointcut("execution(* com.jt.service..*.*(..))")
    public void pointcut(){

    }

    //定义前置通知
    @Before("pointcut()")
    public void before(){
        System.out.println("我是前置通知");
    }
}

1.3 实现Redis缓存

1.3.1 需求分析

1.自定义注解CacheFind 主要被注解标识的方法,则开启缓存的实现.
2.为了将来区分业务,需要在注解中标识key属性,由使用者自行填写.
3.为了用户提供数据超时功能.

1.3.2 自定义注解

@Retention(RetentionPolicy.RUNTIME) //该注解什么时候有效
@Target({ElementType.METHOD})       //对方法有效
public @interface CacheFind {
    String key();               //该属性为必须添加
    int seconds() default 0;    //设定超时时间 默认不超时
}

1.3.3 编辑CacheAOP

package com.jt.aop;

import com.jt.anno.CacheFind;
import com.jt.pojo.ItemDesc;
import com.jt.util.ObjectMapperUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.lang.reflect.Method;
import java.util.Arrays;

@Component  //将对象交给spring容器管理
@Aspect     //标识我是一个切面
public class CacheAOP {

    //1.注入缓存redis对象
    @Autowired
    private Jedis jedis;

    /**
     * 拦截@CacheFind注解标识的方法.
     * 通知选择: 缓存的实现应该选用环绕通知
     * 步骤:
     *  1.动态生成key  用户填写的key+用户提交的参数
     */
    @Around("@annotation(cacheFind)")
    public Object around(ProceedingJoinPoint joinPoint, CacheFind cacheFind){

        //1.如何获取用户在注解中填写的内容呢???  如何获取注解对象....
        String key = cacheFind.key();   //前缀  ITEM_CAT_PARENTID
        //2.如何获取目标对象的参数呢???
        Object[] array = joinPoint.getArgs();
        key += "::"+Arrays.toString(array); // "ITEM_CAT_PARENTID::[0]"

        //3.从redis中获取数据
        Object result = null;
        if(jedis.exists(key)){
            //需要获取json数据之后,直接转化为对象返回!!
            String json = jedis.get(key);
            //如何获取返回值类型
            MethodSignature methodSignature =
                            (MethodSignature) joinPoint.getSignature();
            Class targetClass = methodSignature.getReturnType();
            result = ObjectMapperUtil.toObject(json,targetClass);
            System.out.println("AOP实现缓存的查询!!!");
        }else{
            //key不存在,应该查询数据库
            try {
                result = joinPoint.proceed();    //执行目标方法,获取返回值结果
                String json = ObjectMapperUtil.toJSON(result);
                if(cacheFind.seconds()>0){       //判断是否需要超时时间
                    jedis.setex(key, cacheFind.seconds(), json);
                }else{
                    jedis.set(key,json);
                }
                System.out.println("AOP执行数据库操作!!!");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                throw new RuntimeException(throwable);
            }
        }
        return result;
    }











    /**
     * AOP = 切入点表达式 + 通知方法.
     *
     * 拦截需求:
     *  1.要求拦截itemCatServiceImpl的bean
     *  2.拦截com.jt.service下的所有的类
     *  3.拦截com.jt.service下的所有类及方法
     *  3.1拦截com.jt.service的所有的类.返回值为int类型的.并且add开头
     *  的方法.并且参数一个 为String类型
     */
    //@Pointcut(value = "bean(itemCatServiceImpl)")
    //@Pointcut("within(com.jt.service..*)")
    //拦截com.jt.service下的所有类的所有方法的任意参数类型
    //@Pointcut("execution(int com.jt.service..*.add*(String))")
   /* @Pointcut("execution(int com.jt.service..*.add*(String))")
    public void pointcut(){

    }

    //定义前置通知
    @Before("pointcut()")
    public void before(){
        System.out.println("我是前置通知");
    }*/
}

1.3.4 关于环绕通知参数的说明

问题一:连接点必须位于通知的参数的第一位.

springboot将对象转为XML springboot转json_数据_06


否则报错信息如下:

springboot将对象转为XML springboot转json_json_07


问题二: 其他四大通知了类型是否可以添加ProceedingJoinPoint对象

答案: ProceedingJoinPoint 只能添加到环绕通知中.

报错如下:

springboot将对象转为XML springboot转json_springboot将对象转为XML_08

1.3.5 关于JoinPoint方法说明

/**
     * 要求: 拦截注解方法
     * 打印:
     *      1.打印目标对象的类型
     *      2.打印方法的参数
     *      3.获取目标对象的名称及方法的名称
     * @param joinPoint
     */
    @Before("@annotation(com.jt.anno.CacheFind)")
    public void before(JoinPoint joinPoint){

        Object target = joinPoint.getTarget();  //获取目标对象
        Object[] args = joinPoint.getArgs();    //获取方法参数的
        String targetName =
                joinPoint.getSignature().getDeclaringTypeName(); //获取目标对象的名称
        //获取目标对象的类型
        Class targetClass = joinPoint.getSignature().getDeclaringType();
        //获取目标方法的名称
        String methodName = joinPoint.getSignature().getName();
        System.out.println(target);
        System.out.println(args);
        System.out.println(targetName);
        System.out.println(targetClass);
        System.out.println(methodName);

    }

1.4 商品列表分类实现缓存处理

说明:在业务方法中添加缓存的注解.

/**
     * 分析业务: 通过itemCatId获取商品分类的名称
     * 1.url地址: url:"/item/cat/queryItemName",
     * 2.参数: {itemCatId:val},
     * 3.返回值: 商品分类名称  String
     */
    @RequestMapping("/queryItemName")
    @CacheFind(key="ITEM_CAT_NAME")
    public String findItemCatName(Long itemCatId){

        return itemCatService.findItemCatNameById(itemCatId);
    }