关于java:京淘项目day13

2次阅读

共计 11987 个字符,预计需要花费 30 分钟才能阅读完成。

1.Redis 命令

1.1 入门案例操作

 @Test
    public void testHash() throws InterruptedException {Jedis jedis = new Jedis("192.168.126.129",6379);
        jedis.hset("person", "id", "18");
        jedis.hset("person", "name", "hash 测试");
        jedis.hset("person", "age", "2");
        Map<String,String> map = jedis.hgetAll("person");
        Set<String> set = jedis.hkeys("person");    // 获取所有的 key
        List<String> list = jedis.hvals("person");
    }

    @Test
    public void testList() throws InterruptedException {Jedis jedis = new Jedis("192.168.126.129",6379);
        jedis.lpush("list", "1","2","3","4");
        System.out.println(jedis.rpop("list"));
    }

    @Test
    public void testTx(){Jedis jedis = new Jedis("192.168.126.129",6379);
        //1. 开启事务
       Transaction transaction =  jedis.multi();
       try {transaction.set("a", "a");
           transaction.set("b", "b");
           transaction.set("c", "c");
           transaction.exec();  // 提交事务}catch (Exception e){transaction.discard();
       }
    }

2 SpringBoot 整合 Redis

2.1 编辑 pro 配置文件

因为 redis 的 ip 地址和端口都是动态变化的, 所以通过配置文件标识数据, 因为 redis 是公共局部, 所以写到 common 中.

2.2 编辑配置类

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 RedisConfig {@Value("${redis.host}")
    private String  host;
    @Value("${redis.port}")
    private Integer port;

    @Bean
    public Jedis jedis(){return new Jedis(host, port);
    }
}

3 对象与 JSON 串转化

3.1 对象转化 JSON 入门案例

package com.jt;

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.Date;

public class TestObjectMapper {private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 1. 对象如何转化为 JSON 串的???
     *  步骤:
     *      1. 获取对象的所有的 getXXXX()办法.
     *      2. 将获取的 getXXX 办法的前缀 get 去掉 造成了 json 的 key=xxx
     *      3. 通过 getXXX 办法的调用获取属性的值, 造成了 json 的 value 的值.
     *      4. 将获取到的数据 利用 json 格局进行拼接 {key : value,key2:value2....}
     * 2.JSON 如何转化为对象???
     *      {lyj:xxx}
     *  步骤:
     *      1. 依据 class 参数类型, 利用 java 的反射机制, 实例化对象.
     *      2. 解析 json 格局, 辨别 key:value
     *      3. 进行办法的拼接 setLyj()名称.
     *      4. 调用对象的 setXXX(value) 将数据进行传递,
     *      5. 最终将所有的 json 串中的 key 转化为对象的属性.
     *
     *
     * @throws JsonProcessingException
     */

    @Test
    public void testTOJSON() throws JsonProcessingException {ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(100L).setItemDesc("测试数据转化")
                .setCreated(new Date()).setUpdated(new Date());
        //1. 将对象转化为 JSON

        String json = MAPPER.writeValueAsString(itemDesc);
        System.out.println(json);
        //2. 将 json 转化为对象 src: 须要转化的 JSON 串, valueType: 须要转化为什么对象
        ItemDesc itemDesc2 = MAPPER.readValue(json, ItemDesc.class);
        /**
         * 字符串转化对象的原理:
         */
        System.out.println(itemDesc2.toString());
    }
}

3.2 编辑 ObjectMapper 工具 API

package com.jt.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectMapperUtil {private static final ObjectMapper MAPPER = new ObjectMapper();

    // 将对象转化为 JSON
    public static String toJSON(Object target){
        try {return MAPPER.writeValueAsString(target);
        } catch (JsonProcessingException e) {e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    // 将 JSON 转化为对象
    // 需要: 如果用户传递什么类型, 则返回什么对象
    public static <T> T toObject(String json,Class<T> targetClass){
        try {return MAPPER.readValue(json, targetClass);
        } catch (JsonProcessingException e) {e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

4 实现商品分类缓存实现

4.1 编辑 ItemCatController

阐明: 切换业务调用办法, 执行缓存调用

/**
     * 业务: 实现商品分类的查问
     * url 地址: /item/cat/list
     * 参数:   id: 默认应该 0 否则就是用户的 ID
     * 返回值后果: List<EasyUITree>
     */
    @RequestMapping("/list")
    public List<EasyUITree> findItemCatList(Long id){Long parentId = (id==null)?0:id;
        //return itemCatService.findItemCatList(parentId);
        return itemCatService.findItemCatCache(parentId);
    }

4.2 编辑 ItemCatService

package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.ItemCat;
import com.jt.util.ObjectMapperUtil;
import com.jt.vo.EasyUITree;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
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;

@Service
public class ItemCatServiceImpl implements ItemCatService{

    @Autowired
    private ItemCatMapper itemCatMapper;
    @Autowired(required = false)    // 程序启动是, 如果没有改对象 临时不加载
    private Jedis jedis;


    @Override
    public String findItemCatName(Long itemCatId) {return itemCatMapper.selectById(itemCatId).getName();}


    @Override
    public List<EasyUITree> findItemCatList(Long parentId) {
        //1. 筹备返回值数据
        List<EasyUITree> treeList = new ArrayList<>();
        // 思路. 返回值的数据从哪来? VO  转化 POJO 数据

        //2. 实现数据库查问
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",parentId);
        List<ItemCat> catList = itemCatMapper.selectList(queryWrapper);

        //3. 实现数据的转化  catList 转化为 treeList
        for (ItemCat itemCat : catList){long id = itemCat.getId();  // 获取 ID 值
            String text = itemCat.getName();    // 获取商品分类名称
            // 判断: 如果是父级 应该 closed  如果不是父级 则 open
            String state = itemCat.getIsParent()?"closed":"open";
            EasyUITree easyUITree = new EasyUITree(id,text,state);
            treeList.add(easyUITree);
        }

        return treeList;
    }


    /**
     * Redis:
     *      2 大因素:    key: 业务标识 +::+ 变动的参数  ITEMCAT::0
     *                  value: String  数据的 JSON 串
     * 实现步骤:
     *      1. 应该查问 Redis 缓存
     *          有:  获取缓存数据之后转化为对象返回
     *          没有: 应该查询数据库, 并且将查问的后果转化为 JSON 之后保留到 redis 不便下次应用
     * @param parentId
     * @return
     */
    @Override
    public List<EasyUITree> findItemCatCache(Long parentId) {Long startTime = System.currentTimeMillis();
        List<EasyUITree> treeList = new ArrayList<>();
        String key = "ITEMCAT_PARENT::"+parentId;
        if(jedis.exists(key)){
            //redis 中有数据
            String json = jedis.get(key);
            treeList = ObjectMapperUtil.toObject(json,treeList.getClass());
            Long endTime = System.currentTimeMillis();
            System.out.println("查问 redis 缓存的工夫:"+(endTime-startTime)+"毫秒");
        }else{
            //redis 中没有数据. 应该查询数据库.
            treeList = findItemCatList(parentId);
            // 须要把数据, 转化为 JSON
            String json = ObjectMapperUtil.toJSON(treeList);
            jedis.set(key, json);
            Long endTime = System.currentTimeMillis();
            System.out.println("查询数据库的工夫:"+(endTime-startTime)+"毫秒");
        }
        return treeList;
    }
}

5. AOP 实现 Redis 缓存

5.1 现有代码存在的问题

1. 如果间接将缓存业务, 写到业务层中, 如果未来的缓存代码发送变动, 则代码耦合性高, 必然重写编辑代码
2. 如果其余的业务也须要缓存, 则代码的反复率高, 开发效率低.
  解决方案: 采纳 AOP 形式实现缓存.

5.2 AOP

在软件业,AOP 为 Aspect Oriented Programming 的缩写,意为:面向切面编程,通过预编译形式和运行期间 动静代理 实现程序性能的对立保护的一种技术。AOP 是 OOP 的连续,是软件开发中的一个热点,也是 Spring 框架中的一个重要内容,是函数式编程的一种衍生范型。利用 AOP 能够对业务逻辑的各个局部进行隔离,从而使得业务逻辑各局部之间的耦合度升高,进步程序的可重用性,同时进步了开发的效率。

5.3 AOP 实现步骤

公式: AOP(切面)= 告诉办法(5 种) + 切入点表达式(4 种)

5.3.1 告诉温习

1.before 告诉          在执行指标办法之前执行
2.afterRenturning 告诉 在指标办法执行之后执行 
3.afterThrowing 告诉   在指标办法执行之后报错时执行
4.after 告诉           无论什么时候程序执行实现都要执行的告诉

上述的 4 的告诉类型, 不能控制目标办法是否执行. 个别用来记录程序的执行状态. 个别利用与监控的操作
5.around 告诉(性能最为弱小的)          在指标办法执行前后执行
因为盘绕告诉能够控制目标办法是否执行. 控制程序的执行的轨迹

5.3.2 切入点表达式

1.bean("bean 的 ID")       粒度: 粗粒度 按 bean 匹配 以后 bean 中的办法都会执行告诉
2.within("包名. 类名")    粒度: 粗粒度 能够匹配多个类
3.execution("返回值类型 包名. 类名. 办法名(参数列表)")    粒度: 细粒度 办法参数级别
4.@annotation("包名. 类名") 粒度: 细粒度 依照注解匹配 

5.3.3 AOP 入门案例

package com.jt.aop;

import lombok.extern.apachecommons.CommonsLog;
import org.aspectj.lang.JoinPoint;
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.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Aspect // 标识我是一个切面
@Component  // 交给 Spring 容器治理
public class CacheAOP {

    // 切面 = 切入点表达式 + 告诉办法
    //@Pointcut("bean(itemCatServiceImpl)")
    //@Pointcut("within(com.jt.service.ItemCatServiceImpl)")
    //@Pointcut("within(com.jt.service.*)")   // .* 一级包门路   ..* 所有子孙后代包
    //@Pointcut("execution(返回值类型 包名. 类名. 办法名(参数列表))")
    @Pointcut("execution(* com.jt.service..*.*(..))")
    // 正文: 返回值类型任意类型   在 com.jt.service 下的所有子孙类   以 add 结尾的办法, 任意参数类型
    public void pointCut(){}

    /**
     * 需要:
     *      1. 获取指标办法的门路
     *      2. 获取指标办法的参数.
     *      3. 获取指标办法的名称
     */
    @Before("pointCut()")
    public void before(JoinPoint joinPoint){String classNamePath = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("办法门路:"+classNamePath);
        System.out.println("办法参数:"+ Arrays.toString(args));
        System.out.println("办法名称:"+methodName);
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        try {System.out.println("盘绕告诉开始");
            Object obj = joinPoint.proceed();
            // 如果有下一个告诉, 就执行下一个告诉, 如果没有就执行指标办法(业务办法)
            System.out.println("盘绕告诉完结");
            return null;
        } catch (Throwable throwable) {throwable.printStackTrace();
            throw new RuntimeException(throwable);
        }

    }
}

5.4 AOP 实现 Redis 缓存

5.4.1 业务实现策略

1). 须要自定义注解 CacheFind
2). 设定注解的参数 key 的前缀, 数据的超时工夫.
3). 在办法中标识注解
4). 利用 AOP 拦挡指定的注解
5). 应该应用 Around 告诉实现缓存业务

5.4.2 编辑自定义注解

@Target(ElementType.METHOD)         // 注解对办法无效
@Retention(RetentionPolicy.RUNTIME) // 运行期无效
public @interface CacheFind {public String preKey(); // 定义 key 的前缀
    public int seconds() default 0;   // 定义数据的超时工夫.}

5.4.3 办法中标识注解

5.4.4 编辑 CacheAOP

package com.jt.aop;

import com.jt.anno.CacheFind;
import com.jt.util.ObjectMapperUtil;
import lombok.extern.apachecommons.CommonsLog;
import org.aspectj.lang.JoinPoint;
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 org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

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

@Aspect // 标识我是一个切面
@Component  // 交给 Spring 容器治理
public class CacheAOP {


    @Autowired
    private Jedis jedis;

    /**
     * 注意事项:  当有多个参数时,joinPoint 必须位于第一位.
     * 需要:
     *      1. 筹备 key= 注解的前缀 + 用户的参数
     *      2. 从 redis 中获取数据
     *         有: 从缓存中获取数据之后, 间接返回值
     *         没有: 查询数据库之后再次保留到缓存中即可.
     *
     * 办法:
     *      动静获取注解的类型, 看上去是注解的名称, 然而本质是注解的类型. 只有切入点表达式满足条件
     *      则会传递注解对象类型.
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(cacheFind)")
    public Object around(ProceedingJoinPoint joinPoint,CacheFind cacheFind) throws Throwable {
        Object result = null;   // 定义返回值对象
        String preKey = cacheFind.preKey();
        String key = preKey + "::" + Arrays.toString(joinPoint.getArgs());

        //1. 校验 redis 中是否有数据
        if(jedis.exists(key)){
            // 如果数据存在, 须要从 redis 中获取 json 数据, 之后间接返回
            String json = jedis.get(key);
            //1. 获取办法对象,   2. 获取办法的返回值类型
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            //2. 获取返回值类型
            Class returnType = methodSignature.getReturnType();
            result = ObjectMapperUtil.toObject(json,returnType);
            System.out.println("AOP 查问 redis 缓存!!!");
        }else{
            // 代表没有数据, 须要查询数据库
            result = joinPoint.proceed();
            // 将数据转化为 JSON
            String json = ObjectMapperUtil.toJSON(result);
            if(cacheFind.seconds() > 0){jedis.setex(key, cacheFind.seconds(), json);
            }else{jedis.set(key,json);
            }
            System.out.println("AOP 查询数据库!!!");
        }
        return result;
    }






   /* @Around("@annotation(com.jt.anno.CacheFind)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //1. 获取指标对象的 Class 类型
        Class targetClass = joinPoint.getTarget().getClass();
        //2. 获取指标办法名称
        String methodName = joinPoint.getSignature().getName();
        //3. 获取参数类型
        Object[] argsObj = joinPoint.getArgs();
        Class[]  argsClass = null;
        //4. 对象转化为 class 类型
        if(argsObj.length>0){argsClass = new Class[argsObj.length];
            for(int i=0;i<argsObj.length;i++){argsClass[i] = argsObj[i].getClass();}
        }
        //3. 获取办法对象
        Method targetMethod = targetClass.getMethod(methodName,argsClass);

        //4. 获取办法上的注解
        if(targetMethod.isAnnotationPresent(CacheFind.class)){CacheFind cacheFind = targetMethod.getAnnotation(CacheFind.class);
            String key = cacheFind.preKey() + "::"
                         +Arrays.toString(joinPoint.getArgs());
            System.out.println(key);
        }

        Object object = joinPoint.proceed();
        System.out.println("盘绕开始后");
        return object;
    }
*/









   /* // 切面 = 切入点表达式 + 告诉办法
    //@Pointcut("bean(itemCatServiceImpl)")
    //@Pointcut("within(com.jt.service.ItemCatServiceImpl)")
    //@Pointcut("within(com.jt.service.*)")   // .* 一级包门路   ..* 所有子孙后代包
    //@Pointcut("execution(返回值类型 包名. 类名. 办法名(参数列表))")
    @Pointcut("execution(* com.jt.service..*.*(..))")
    // 正文: 返回值类型任意类型   在 com.jt.service 下的所有子孙类   以 add 结尾的办法, 任意参数类型
    public void pointCut(){}*/

    /**
     * 需要:
     *      1. 获取指标办法的门路
     *      2. 获取指标办法的参数.
     *      3. 获取指标办法的名称
     */
   /* @Before("pointCut()")
    public void before(JoinPoint joinPoint){String classNamePath = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("办法门路:"+classNamePath);
        System.out.println("办法参数:"+ Arrays.toString(args));
        System.out.println("办法名称:"+methodName);
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        try {System.out.println("盘绕告诉开始");
            Object obj = joinPoint.proceed();
            // 如果有下一个告诉, 就执行下一个告诉, 如果没有就执行指标办法(业务办法)
            System.out.println("盘绕告诉完结");
            return null;
        } catch (Throwable throwable) {throwable.printStackTrace();
            throw new RuntimeException(throwable);
        }
    }*/
}
正文完
 0