This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

4YE brings the last article of the theme month.

This article is divided into two parts, the first part is about installing EasyMock, and the second part is about implementing easyMock through a small project (Springboot2+Quartz+MybatisPlus+ EasyMock).

Easy – the mock – the docker’s official website

Go directly to πŸ˜„

Easy-mock-docker official address: github.com/easy-mock/e…

Installation steps are shown in the figure below:

Docker – compose the installation

This installation is relatively simple, perform the following three steps to complete πŸ˜€

Docker – compose website address: docs.docker.com/compose/ins…

The setup steps are as follows: ✌

Download the docker – compose

sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
Copy the code

To give permission

sudo chmod +x /usr/local/bin/docker-compose
Copy the code

Check the version

docker-compose --version
Copy the code

The configuration file

Prepare the following two configuration files. πŸ˜„

docker-compose.yml

Bloggers map easyMock files to /home/ryzeyang/easyMock, and friends can modify them to their own πŸ˜„

version: '3'

services:
  mongodb:
    image: Mongo: 3.4.1 track
    volumes:
      #./data/db Address for storing database files. Change it to a local address if necessary
      - '/home/ryzeyang/easymock/data/db:/data/db'
    networks:
      - easy-mock
    restart: always

  redis:
    image: Redis: 4.0.6
    command: redis-server --appendonly yes
    volumes:
      #./data/redis Redis the address where data files are stored. If necessary, change it to a local address
      - '/home/ryzeyang/easymock/data/redis:/data'
    networks:
      - easy-mock
    restart: always

  web:
    image: Easymock/easymock: 1.6.0
    command: /bin/bash -c "npm start"
    ports:
      - 7300: 7300
    volumes:
      If necessary, change the address to a local address
      - '/home/ryzeyang/easymock/logs:/home/easy-mock/easy-mock/logs'
      Configure the address, please use the local configuration address replacement
      - '/home/ryzeyang/easymock/production.json:/home/easy-mock/easy-mock/config/production.json'
    networks:
      - easy-mock
    restart: always

networks:
  easy-mock:


Copy the code

production.json

This is the revised version according to the official website. πŸ˜‹

{
  "port": 7300."host": "0.0.0.0"."pageSize": 30."proxy": false."db": "mongodb://mongodb/easy-mock"."unsplashClientId": ""."redis": {
    "keyPrefix": "[Easy Mock]"."port": 6379."host": "redis"."password": ""."db": 0
  },
  "blackList": {
    "projects": []."ips": []},"rateLimit": {
    "max": 1000."duration": 1000
  },
  "jwt": {
    "expire": "14 days"."secret": "shared-secret"
  },
  "upload": {
    "types": [".jpg".".jpeg".".png".".gif".".json".".yml".".yaml"]."size": 5242880."dir": ".. /public/upload"."expire": {
      "types": [".json".".yml".".yaml"]."day": - 1}},"ldap": {
    "server": ""."bindDN": ""."password": ""."filter": {
      "base": ""."attributeName": ""}},"fe": {
    "copyright": ""."storageNamespace": "easy-mock_"."timeout": 25000."publicPath": "/dist/"}}Copy the code

Start the

Create the logs folder in the configuration file.

Error: EACCES: Permission denied

You can use XFTP to upload the above configuration file to the easyMock directory and then execute the following command to start docker-compose up so that it does not run in the background and you can see if the project runs successfully 🐷

Address: http://192.168.80.128:7300

Attention!connect EHOSTUNREACHerror

This is because we use network to achieve interconnection between containers, which is why the configuration should be changed to mogodb and redis instead of localhost🐷

These two names are actually the names of services in our Dockerfile

The simple and crude method is as follows:

If it doesn’t start! Check the firewall!!

Sudo systemctl stop firewalld. Service πŸ˜„

After the firewall is disabled, restart the docker systemctl restart docker.service

Docker-compose up -d in the background

His IP access address: http://192.168.80.128:7300 with 😁

Results the following

After the environment is built, we can mock the data as follows! πŸ˜„

Springboot2+Quartz+MybatisPlus+easymock

Main functions:

Use EasyMock to simulate the data, use restTemplate to get the mock data, use Jackson to convert JSON to entity classes, use MybatisPlus to store data in bulk, implement a timed job through Quartz, repeat the above steps.

Get familiar with this MP and learn about EasymockπŸ˜„

This happened on the day of S10 when I was studying the Mysql Innodb index and watching the game, I was thinking of making some random data to fill in DB and try MybaitsPlus and using easyMock to mock some data 😝

Mysql

Look at the time, there are more than two million ~

Build table Sql to the following one – based! I forgot to change it in other articles (I directly used the one in the test, which is somewhat different).

Create table user
CREATE TABLE `test_user`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'user ID',
  `user_name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'User name',
  `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'Mobile number',
  `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'email',
  `ip` varbinary(4) NOT NULL COMMENT 'IP',
  `create_time` datetime(0) NOT NULL COMMENT 'Creation time',
  `update_time` datetime(0) NOT NULL COMMENT 'Update Time'.PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB  CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

Copy the code

Easymock

The data format is as follows:

Click preview to see the image below:

Json text

If the timeout is set too large, it may timeout 😱

{
  "data|500-2000": [{
    "userId": '@guid',
    "userName": '@cname',
    "phone": / ^1[385] [19 -]\d{8}/,
    "email": "@email"."ip": "@ip"."createTime": "@datetime('yyyy-MM-dd HH:mm:ss')"}}]Copy the code

The main code

The Job profile

Use the RestTemplate to fetch mock data, and use Jackson parsing to fetch User information and deserialize it into an object. Note that the createTime attribute of the User entity is LocalDateTime. Add those two lines of code! Otherwise Jackson couldn’t help us with the deserialization.

package com.java4ye.demo.job;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.java4ye.demo.entity.User;
import com.java4ye.demo.service.IUserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StopWatch;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/ * * *@author Java4ye
 * @date2021/1/11 23:16 * @wechat official number: Java4ye *@GitHubhttps://github.com/RyzeYang * @ blog https://blog.csdn.net/weixin_40251892 * /
@Slf4j
public class GetMockUserJob extends QuartzJobBean {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    IUserService userService;

    @SneakyThrows
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobKey key = jobExecutionContext.getJobDetail().getKey();
        log.info("GetMockUserJob start: ");
        ResponseEntity<String> forEntity = restTemplate.getForEntity("Http://192.168.80.128:7300/mock/5f8c1175994a570020e4dfe4/user/arry#! method=get", String.class);
        HttpStatus statusCode = forEntity.getStatusCode();
        if (statusCode.is2xxSuccessful()) {
            String body = forEntity.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(body);
            JsonNode data = jsonNode.get("data");
            System.out.println(data);
            // LocalDateTime solution
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            objectMapper.registerModule(new JavaTimeModule());
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, User.class);
            List<User> users = objectMapper.readValue(data.toString(), javaType);
            StopWatch stopWatch = new StopWatch("save mock users");
            stopWatch.start("save mock users");
// Try inserting a user
            User user = users.get(0);
            userService.save(user);
// Insert users in batches
// userService.saveBatch(users,5000);stopWatch.stop(); System.out.println(stopWatch.prettyPrint()); }}}Copy the code

UserMapper file

The INSERT method was overridden primarily to customize the IP fieldINET6_NTOA(ip)


      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.java4ye.demo.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.java4ye.demo.entity.User">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="user_id" jdbcType="VARCHAR" property="userId" />
        <result column="user_name" jdbcType="VARCHAR" property="userName" />
        <result column="phone" jdbcType="VARCHAR" property="phone" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
    </resultMap>
    <resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="com.java4ye.demo.entity.User">
        <result column="ip" jdbcType="VARBINARY" property="ip"/>
    </resultMap>
    <sql id="Base_Column_List">
        id, user_id, user_name, phone, email, create_time, update_time
    </sql>
    <sql id="Blob_Column_List">
        INET6_NTOA(ip)
    </sql>
    <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.java4ye.demo.entity.User" useGeneratedKeys="true">
        insert into test_user (user_id, user_name, phone,
                               email, create_time, update_time,
                               ip)
        values (#{userId,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR},
                #{email,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP},
                INET6_ATON(#{ip,jdbcType=VARBINARY}))
    </insert>

</mapper>
Copy the code

Running effect

Insert single data

Bulk insert

You can see that it took 1781ms to insert 873 users

Project address :(interested partners can go to see ~ if there is help, please remember to give a star oh ~😝 thank you for your support!)

GitHub project address: github.com/RyzeYang/sp…

I am 4ye and we will see you next time γƒΎ(οΏ£β–½οΏ£)Bye Bye

Welcome attention, make a friend!! (β€’Μ€ Ο‰ ‒́)y

Hey hey like to support below πŸ˜‹

Let’s start this unexpected meeting! ~

Welcome to leave a message! Thanks for your support! O (≧ γƒΎ del ≦ *)