外卖小程序02

数据库索引

介绍

索引是一种可以帮助数据库高效查询数据的数据结构

优点

1.提高查询效率,减少磁盘IO次数,降低数据库IO成本

2.使用索引列进行数据排序,降低数据库排序成本,降低CPU消耗

缺点

1.索引需要占用存储空间

2.索引虽然提高了查询效率,但同时也降低了insert,update,delete的效率

结构

MySQL数据库支持的索引结构有很多,如:Hash索引、B+Tree索引、Full-Text索引等。

我们平常所说的索引,如果没有特别指明,都是指默认的 B+Tree 结构组织的索引。

问题

为什么不使用红黑树或者二叉搜索树作为索引的数据结构?

回答

假设数据结构为红黑树,如果此时存在1000万条数据,根据计算树的高度在23左右,那么一个用户可能就需要23次磁盘IO,高并发情况下,例如有100万用户同时访问,那么访问效率就会极其低下.

B+Tree数据结构

为了降低树的高度,就需要增加树的宽度,每个节点里面不能只存储一个数据,为此引入了一种新的数据结构:B+Tree结构,如下图:

请添加图片描述

介绍

每一个节点,可以存储多个key和多个指针

叶子节点:最后一层的节点,用于存储数据

非叶子节点:存储的是键和指针,用于索引数据

为提高数据的范围查询效率,所有叶子节点形成了一个双向链表,便于数据的排序和范围查询

拓展

非叶子节点都是由key和指针构成的,每个key占8个字节,每个指针占6个字节,每个节点的总容量是16KB,那么一个节点就可以存储1024*16/(6+8)=1170个元素

查看mysql索引节点大小:show global status like ‘innodb_page_size’; – 节点大小:16384

当根节点中村存储了1170个元素时,每个元素的指针所指向的第二层节点中也存储了1170个元素,故仅仅两次磁盘IO就可以查询到大约1170*1170 = 135W条数据

根据第二层的指针,又可以找到第三层的节点,假设第三层的元素节点中key+数据的总大小为1KB,那么每个节点就可以存储16条数据,三次磁盘IO所能查找到的总数据条数为:16*135W=2000W+条

优点

1.千万条数据,树的高度小于等于3

2.所有数据存储在叶子节点中,底层已经实现了按照索引进行排序,支持范围查询.叶子节点为双向链表结构,支持从小到大和从大到小查找

语法

创建索引
create [unique] index 索引名 on 表名(字段名,...); 
查看索引
show index from 表名;
删除索引
drop index 索引名 on 表名;

全局异常处理器

需求

处理数据库唯一字段重复添加异常

代码实现

package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器,处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理SQL异常
     * @param ex SQL违反唯一约束条件异常
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'lxh' for key 'employee.idx_username'
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username+ MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}

ThreadLocal

介绍

Thread的局部变量,为每个线程提供一份独有的存储空间,具有线程隔离的效果,只有在线程内才能获取ThreadLocal中的数据,线程外无法访问.

常用方法

1.public void set(T value):设置当前线程局部变量值

2.public T get():获取当前线程局部变量值

3.public void remove():删除当前线程中的局部变量值

案例

需求

在进行数据库操作时,记录操作人的id

步骤

1.定义一个类实现ThreadLocal类存储局部变量的功能

2.在解析jwt令牌时,将登陆用户的id存入ThreadLocal中

3.进行数据库操作时,获取并记录操作人的id

代码实现

BaseContext
package com.sky.context;

/**
 * 实现ThreadLocal的线程局部变量存储
 */
public class BaseContext {

    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    public static void setCurrentId(Long id) {
        threadLocal.set(id);
    }

    public static Long getCurrentId() {
        return threadLocal.get();
    }

    public static void removeCurrentId() {
        threadLocal.remove();
    }
}
JwtTokenAdminInterceptor
package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法,直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("当前员工id:", empId);
            //将员工id存入ThreadLocal中
            BaseContext.setCurrentId(empId);
            //3、通过,放行
            return true;
        } catch (Exception ex) {
            //4、不通过,响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
EmployeeServiceImpl
@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 更新员工信息
     * @param employeeDTO 前端传递的员工数据模型
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);

        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }
}

日期类型格式化

需求

将日期时间按照规定的格式显示

实现

方案一:

给日期时间属性加上@JsonFormat注解

eg:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocaldateTime updateTime;
缺点:

需要在每个属性上加注解,比较繁琐,不能全局处理

方案二:

使用SpringMVC的消息转换器,对日期类型格式进行统一处理
即修改Jackson的默认转换格式,在配置文件中修改底层的ObjectMapper(Jackson的核心对象,可以实现序列化和反序列化)

代码实现
    /**
     * 扩展SpringMVC的消息转换器,统一对日期类型进行格式处理
     * @param converters 消息转换器集合
     */
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters){
        log.info("扩展消息转换器");
        //创建一个消息转换器对象
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //需要为消息转换器设置一个对象转换器,将java对象转换为json对象
        converter.setObjectMapper(new JacksonObjectMapper());
        //将自己的消息转换器加入容器当中
        converters.add(0,converter);
    }
对象转换器
package com.sky.json;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;

/**
 * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
 * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
 * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
 */
public class JacksonObjectMapper extends ObjectMapper {

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    //public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    public JacksonObjectMapper() {
        super();
        //收到未知属性时不报异常
        this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);

        //反序列化时,属性不存在的兼容处理
        this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        SimpleModule simpleModule = new SimpleModule()
                .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
                .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        //注册功能模块 例如,可以添加自定义序列化器和反序列化器
        this.registerModule(simpleModule);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值