1. Create a new table in the database
Because it needs to be stored in the database, I didn't make this table very large according to your actual business, because it will be deleted in less than a few days.
Table names and fields are as you like:
Table name: biz_ monitor_ time
Id int 5 is not null. The primary key is incremented automatically
request_ Address varchar 50 is not a null request address
waste_ Time int 5 is not null time consuming
create_ Time datetime default value now() is not null creation time
2. Generate code based on the created table
These are the layers: mapper, service, serviceimpl and controller
You can use the code generator to generate automatically. Of course, you can also do it by hand. If you don't want to do it by hand and don't have a generator, I'll post the code below,
For your reference:
domain :
package com.cema.manage.project.manage.monitorTime.domain;
/**
*Statistics of HTTP request response schedule biz_ monitor_ time
*
* @author reasahi
* @date 2021-04-27
*/
@TableName(value = "biz_monitor_time")
public class MonitorTime extends Model<MonitorTime> {
private static final long serialVersionUID = 1L;
/**
*Primary key
*/
@TableId(value = "id")
private Integer id;
/**
*Request address
*/
@TableField(value = "request_address")
private String requestAddress;
/**
*Time consuming
*/
@TableField(value = "waste_time")
private Integer wasteTime;
/**
*Creation time
*/
@TableField(value = "create_time")
private Date createTime;
/**
*Settings: primary keys
*/
public void setId(Integer id) {
this.id = id;
}
/**
*Get: primary key
*/
public Integer getId() {
return id;
}
/**
*Setting: request address
*/
public void setRequestAddress(String requestAddress) {
if (requestAddress != null) {
if (requestAddress.trim().isEmpty()) {
this.requestAddress = null;
} else {
this.requestAddress = requestAddress;
}
}
}
/**
*Get: request address
*/
public String getRequestAddress() {
return requestAddress;
}
/**
*Settings: time consuming
*/
public void setWasteTime(Integer wasteTime) {
this.wasteTime = wasteTime;
}
/**
*Getting: time consuming
*/
public Integer getWasteTime() {
return wasteTime;
}
/**
*Setting: creation time
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
*Get: creation time
*/
public Date getCreateTime() {
return createTime;
}
@Override
protected Serializable pkVal() {
return this.id;
}
}
mapper :
package com.cema.manage.project.manage.monitorTime.mapper;
/**
*Statistics of HTTP request response time data layer
*
* @author reasahi
* @date 2021-04-27
*/
public interface MonitorTimeMapper extends BaseMapper<MonitorTime>
{
void insertMonitorTime(MonitorTime monitorTime);
}
xml :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cema.manage.project.manage.monitorTime.mapper.MonitorTimeMapper">
<!-- biz_monitor_time -->
<resultMap id="resultMapMonitorTime" type="com.cema.manage.project.manage.monitorTime.domain.MonitorTime">
<id column="id" property="id"></id>
<result column="request_address" property="requestAddress"></result>
<result column="waste_time" property="wasteTime"></result>
<result column="create_time" property="createTime"></result>
</resultMap>
<insert id="insertMonitorTime" parameterType="com.cema.manage.project.manage.monitorTime.domain.MonitorTime">
INSERT INTO biz_monitor_time (request_address, waste_time)
VALUES (#{requestAddress}, #{wasteTime});
</insert>
</mapper>
service :
package com.cema.manage.project.manage.monitorTime.service;
/**
*Statistics of HTTP request response time service layer
*
* @author reasahi
* @date 2021-04-27
*/
public interface IMonitorTimeService extends IService<MonitorTime>
{
void insertMonitorTime(MonitorTime monitorTime);
}
serviceImpl :
explain:
The @ async (“asyncserviceexecutor”) in the code is the name of the bean of the asynchronous service executor created by the asyncserviceexecutor in the asynchronous call. In fact, it is a thread pool. I throw it in for asynchronous processing. You can roll it yourself or copy someone else’s. If you don’t like hand rolling, I’ll post it below for your reference:
package com.cema.manage.project.manage.monitorTime.service;
/**
*Statistical HTTP request response time service layer implementation
*
* @author reasahi
* @date 2021-04-27
*/
@Service
public class MonitorTimeServiceImpl extends ServiceImpl<MonitorTimeMapper, MonitorTime> implements IMonitorTimeService {
@Resource
private MonitorTimeMapper monitorTimeMapper;
@Override
@Async("asyncServiceExecutor")
public void insertMonitorTime(MonitorTime monitorTime) {
monitorTimeMapper.insertMonitorTime(monitorTime);
}
}
Asynchronous task configuration:
package com.cema.manage.config;
@Configuration
@EnableAsync
public class AsyncTaskConfig {
@Bean(name = "asyncServiceExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPool = new VisiableThreadPoolTaskExecutor();
//Set the number of core threads
threadPool.setCorePoolSize(1000);
//Set the maximum number of threads
threadPool.setMaxPoolSize(1000000);
//The buffer queue used by the thread pool
threadPool.setQueueCapacity(Integer.MAX_VALUE);
//Waiting for the task to complete at shutdown -- indicates waiting for all threads to complete execution
threadPool.setWaitForTasksToCompleteOnShutdown(true);
//The waiting time (0 by default, which will stop immediately) is not forced to stop after XX seconds
threadPool.setAwaitTerminationSeconds(60);
//Thread name prefix
threadPool.setThreadNamePrefix("Derry-Async-");
//Initialize thread
threadPool.initialize();
return threadPool;
}
}
Controller: no change required.
3. Implement interceptor
Description: assign value to imonitortimeservice through construction method.
package com.cema.manage.config.Interceptor;
@Component
public class MonitoringTimeInterceptor implements HandlerInterceptor {
private IMonitorTimeService iMonitorTimeService;
public MonitoringTimeInterceptor(IMonitorTimeService iMonitorTimeService) {
this.iMonitorTimeService = iMonitorTimeService;
}
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
long start = System.currentTimeMillis();
httpServletRequest.setAttribute("start", start);
return true;
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
long start = (Long) httpServletRequest.getAttribute("start");
long end = System.currentTimeMillis() - start;
String uri = httpServletRequest.getRequestURI();
MonitorTime monitorTime = new MonitorTime();
monitorTime.setRequestAddress(uri);
monitorTime.setWasteTime((int) end);
iMonitorTimeService.insertMonitorTime(monitorTime);
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
}
4. Inherit the webmvc configuration adapter to add your interceptor and make it work
explain:
Registry. Addinterceptor (here is the interceptor you just wrote. Let’s assign values through the constructor). Addpathpatterns (fill in the URL you need to intercept. Go to your controller layer, such as: “/ PFS / * *”).
package com.cema.manage.config;
@Configuration
public class ViewConfigure extends WebMvcConfigurerAdapter {
@Resource
private IMonitorTimeService iMonitorTimeService;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//. addpathpatterns ("/ * *") // intercept all requests / upload / ecology
registry.addInterceptor(new MonitoringTimeInterceptor(iMonitorTimeService))
.addPathPatterns("/token/**")
;
}
}
5. Summary
The code part is finished. In the future, all HTTP requests that enter your interceptor will be stored in the database, as shown in the following figure:
You can judge whether optimization is needed according to the response time of each interface. You can use some aggregate functions in the database to see the interface with the maximum response time, or the average response time of an interface, etc. Of course, this is just a very simple interceptor and data storage. You can make a better one.
byeBye ^ ^~