mysql分表spring拦截器进行日志采集

public Date getCreate_time() {

return create_time;

}

public void setCreate_time(Date create_time) {

this.create_time = create_time;

}

public Date getState_time() {

return state_time;

}

public void setState_time(Date state_time) {

this.state_time = state_time;

}

public Date getEnd_time() {

return end_time;

}

public void setEnd_time(Date end_time) {

this.end_time = end_time;

}

}

拦截器采集日志

id是用redis生成的小伙伴可以用别的

新增语句这里就不贴出来了

以下操作查询的放一个表

其他放一张表

package com.web.common.intercept;

import cn.hutool.core.date.DateUtil;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.serializer.SerializerFeature;

import com.web.common.controller.BaseController;

import com.web.entity.TbLogging;

import com.web.entity.TbLoggingSelect;

import nl.bitwalker.useragentutils.UserAgent;

import org.apache.commons.beanutils.BeanUtils;

import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.method.HandlerMethod;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import redis.clients.jedis.Jedis;

import web.dao.hsdao.TbLoggingMapper;

import web.dao.hsdao.TbLoggingSelectMapper;

import web.util.JedisUtil;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.util.Date;

/**

  • @ClassName SginAop

  • @Description

  • @Author heng

  • @Date 2020/4/26 10:41

  • @Version 1.0

*/

public class LogInterceptor extends HandlerInterceptorAdapter {

private final String redisKey = “LOG:LOGGING_KEY”;

private final static Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);

//请求开始时间标识

private static final String LOGGER_SEND_TIME = “_send_time”;

//请求日志实体标识

private static final String LOGGER_ENTITY = “_logger_entity”;

@Autowired

private TbLoggingSelectMapper tbLoggingSelectMapper;

@Autowired

private TbLoggingMapper tbLoggingMapper;

public Long incr(String key) {

Jedis jedis =JedisUtil.getJedis();

try {

return jedis.incr(key);

} finally {

if (null != jedis) {

jedis.close();

}

}

}

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {

try {

TbLogging tbLogging = new TbLogging();

Long start_long_time = System.currentTimeMillis();

tbLogging.setState_time(DateUtil.date(start_long_time));

//获取ip

tbLogging.setIp(getRemoteHost(request));

//获取控制器的名字

tbLogging.setClass_name(((HandlerMethod) handler).getBean().getClass().getName());

//获取方法名

tbLogging.setMethod_name(((HandlerMethod) handler).getMethod().getName());

//获取请求参数信息

String param = JSON.toJSONString(request.getParameterMap(),

SerializerFeature.DisableCircularReferenceDetect,

SerializerFeature.WriteMapNullValue);

tbLogging.setParam(param);

try {

tbLogging.setCreate_user_id(new BaseController().obtainLoginUserId(request));

}catch (Exception ex){

LOGGER.info(“拿到当前登录人失败”);

}

//请求方法

tbLogging.setMethod(request.getMethod());

//请求url到后端的url

tbLogging.setUrl(request.getRequestURI());

//浏览器

//获取浏览器信息

String ua = request.getHeader(“User-Agent”);

//转成UserAgent对象

UserAgent userAgent = UserAgent.parseUserAgentString(ua);

tbLogging.setBrowser(userAgent.toString());

//获取返回值

//tbLogging.setReturn_value(response.getWriter().toString());

//设置请求开始时间

request.setAttribute(LOGGER_SEND_TIME, start_long_time);

//设置请求实体到request内,方便afterCompletion方法调用

request.setAttribute(LOGGER_ENTITY, tbLogging);

} catch (Exception e) {

LOGGER.info(“日志添加失败”);

}

}

return true;

}

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

}

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

try {

String uri = request.getRequestURI();

String contextPath = request.getContextPath();

if (StringUtils.length(contextPath) > 0) {

contextPath = StringUtils.substring(uri, contextPath.length());

}

TbLogging tbLogging = (TbLogging) request.getAttribute(LOGGER_ENTITY);

//获取请求错误码

int status = response.getStatus();

//当前时间

long currentTime = System.currentTimeMillis();

//请求开始时间

long time = Long.valueOf(request.getAttribute(LOGGER_SEND_TIME).toString());

//获取本次请求日志实体

tbLogging.setState(status+“”);

//设置请求时间差

tbLogging.setLong_time((currentTime - time)+“”);

tbLogging.setEnd_time(DateUtil.date(currentTime));

tbLogging.setCreate_time(DateUtil.date(currentTime));

// Long longId = IdUtil.createSnowflake(1, 1).nextId();

Long longId = incr(redisKey);

tbLogging.setId(longId.intValue());

if(tbLogging.getClass_name().indexOf(“TbLoggingController”) == -1){

if (contextPath.indexOf(“search_”) == -1

&& !tbLogging.getMethod_name().startsWith(“search”)

&& !tbLogging.getMethod_name().startsWith(“get”)

&& !tbLogging.getMethod_name().startsWith(“query”)

&& !tbLogging.getMethod_name().startsWith(“find”)

&& !tbLogging.getMethod_name().startsWith(“select”)

&& !tbLogging.getMethod_name().equals(“index”)) {

//执行将日志写入数据库,可以根据实际需求进行保存

// sysLogRepo.save(sysLog);

tbLoggingMapper.insertTbLogging(tbLogging);

}else {

TbLoggingSelect select = new TbLoggingSelect();

//把tbLogging的值给select

BeanUtils.copyProperties(select,tbLogging);

tbLoggingSelectMapper.insertTbLoggingSelect(select);

}

}

}catch (Exception e){

LOGGER.info(“日志添加失败”);

}

}

public int difference(Date nowDate, String decrypted){

return Math.abs((int)(nowDate.getTime()-Long.valueOf(decrypted))/1000);

}

/**

  • @Title: getRemoteHost

  • @Description: 获取Ip地址

  • @return: String

  • @version V1.0

*/

public String getRemoteHost(HttpServletRequest request) {

String ip = request.getHeader(“x-forwarded-for”);

if (ip == null || ip.length() == 0 || “unknown”.equalsIgnoreCase(ip)) {

ip = request.getHeader(“Proxy-Client-IP”);

}

if (ip == null || ip.length() == 0 || “unknown”.equalsIgnoreCase(ip)) {

ip = request.getHeader(“WL-Proxy-Client-IP”);

}

if (ip == null || ip.length() == 0 || “unknown”.equalsIgnoreCase(ip)) {

ip = request.getHeader(“HTTP_CLIENT_IP”);

}

if (ip == null || ip.length() == 0 || “unknown”.equalsIgnoreCase(ip)) {

ip = request.getHeader(“HTTP_X_FORWARDED_FOR”);

}

if (ip == null || ip.length() == 0 || “unknown”.equalsIgnoreCase(ip)) {

ip = request.getRemoteAddr();

}

return ip.equals(“0:0:0:0:0:0:0:1”) ? “127.0.0.1” : ip;

}

}

以下操作用于查询

mapper.xml

/**

  • 用于分表分页查询

  • @param map

  • @return

*/

List pageListTbLoggingSelectByObj(Map<String,Object> map);

int pageListTbLoggingSelectByObjCount(Map<String,Object> map);

SELECT

FROM tb_logging_select

is_delete = 0

AND date_format(create_time,‘%Y-%m-%d’) = #{create_time}

AND id > #{maxId}

AND id < #{minId}

order by id asc

order by id desc

order by id desc

LIMIT #{pageSize}

SELECT count(1)

FROM tb_logging_select

is_delete = 0

AND date_format(create_time,‘%Y-%m-%d’) = #{create_time}

/**

  • 用于分表分页查询

  • @param map

  • @return

*/

List pageListTbLoggingByObj(Map<String,Object> map);

int pageListTbLoggingByObjCount(Map<String,Object> map);

SELECT

FROM tb_logging

is_delete = 0

AND date_format(create_time,‘%Y-%m-%d’) = #{create_time}

AND id > #{maxId}

AND id < #{minId}

order by id asc

order by id desc

order by id desc

LIMIT #{pageSize}

SELECT count(1)

FROM tb_logging

is_delete = 0

AND date_format(create_time,‘%Y-%m-%d’) = #{create_time}

service

package web.service.logging;

import com.web.common.util.PropertyValueChangeUtil;

import com.web.common.util.web.BeanRefUtil;

import com.web.entity.TbLogging;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import web.dao.hsdao.TbLoggingMapper;

import web.dao.hsdao.TbLoggingSelectMapper;

import web.util.ResultUtils;

import java.util.*;

/**

  • 项目名称:

  • 类 名 称:TbLoggingService

  • 类 描 述:TODO

  • 创建时间:2020/6/12 17:25

  • 创 建 人:heng

*/

@Service

public class TbLoggingService {

@Autowired

private TbLoggingMapper tbLoggingMapper;

@Autowired

private TbLoggingSelectMapper tbLoggingSelectMapper;

public ResultUtils findLoging(Map<String,Object> map){

Integer pageSize = Integer.valueOf( map.get(“pageSize”).toString());

List tbLoggings = tbLoggingMapper.pageListTbLoggingByObj(map);

List tbLoggingSelects = tbLoggingSelectMapper.pageListTbLoggingSelectByObj(map);

int count1 = tbLoggingMapper.pageListTbLoggingByObjCount(map);

int count2 = tbLoggingSelectMapper.pageListTbLoggingSelectByObjCount(map);

tbLoggings.addAll(tbLoggingSelects);

List list = new ArrayList<>();

if (map.get(“maxId”) != null){

Collections.sort(tbLoggings, new Comparator() {

@Override

public int compare(TbLogging o1, TbLogging o2) {

if (o1.getId()> o2.getId()){

return 1;

}

if(o1.getId()< o2.getId()){

return -1;

}

return 0;

}

});

if (tbLoggings.size() >= pageSize){

list = tbLoggings.subList(0,pageSize);

}else {

list = tbLoggings;

}

Collections.sort(list, new Comparator() {

@Override

public int compare(TbLogging o1, TbLogging o2) {

if (o1.getId()< o2.getId()){

return 1;

}

if(o1.getId()> o2.getId()){

return -1;

}

return 0;

}

});

}else{

Collections.sort(tbLoggings, new Comparator() {

@Override

public int compare(TbLogging o1, TbLogging o2) {

if (o1.getId()< o2.getId()){

return 1;

}

if(o1.getId()> o2.getId()){

return -1;

}

return 0;

}

});

if (tbLoggings.size() >= pageSize){

list = tbLoggings.subList(0,pageSize);

}else {

list = tbLoggings;

}

}

List mapRows = new ArrayList();

for (TbLogging d : list) {

BeanRefUtil beanRefUtil = new BeanRefUtil();

Map map1 = beanRefUtil.transBean2Map(d);

// 2.自定义按钮设置在此处

map1.put(“maxId”,list.get(0).getId());

map1.put(“minId”,list.get(list.size()-1).getId());

//下面的方法是将对象中的枚举值改为枚举描述。如stat为0时表示无效。则将map中的stat的值从0改为0-无效,方便前端显示,但是该方法需要完善Dto的PropertyEnum方法

PropertyValueChangeUtil.dateValue2Desc(map1 );

mapRows.add(map1);

}

return new ResultUtils(mapRows,count1+count2);

}

}

controller 这里的maxId和minId是存前端传来的第一次查询为空会查询全部的

然后排序各取10条进行合并分页  第一次查询后会把合并后的最大id和最小id存到前端等第二次点上一页或者下一页的时候传入

点下一页的时候传入 minId 点上一页的时候传入maxId因为是desc排序原因 只能传入一个 点上一页或者下一页传入

package com.web.controller;

import com.web.common.controller.BaseController;

import com.web.common.exception.BusinessException;

import com.web.common.util.ConstantValue;

import com.web.common.util.web.PagingObject;

import com.web.common.util.web.PangingUtils;

import org.apache.commons.collections.map.HashedMap;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Java开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
ort com.web.common.util.web.PangingUtils;

import org.apache.commons.collections.map.HashedMap;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-Uj9cUWp2-1715847535085)]

[外链图片转存中…(img-dV8rNmSw-1715847535086)]

[外链图片转存中…(img-Grtk2zk9-1715847535086)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Java开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值