xxl-job for beginners (nanny-level introductory tutorial)

Hits: 0

Article directory

foreword

The official documentation of this distributed timer (the link below the official website) has been explained very clearly, and I will not repeat
the xxl-job that I just learned today. Going deeper, today’s goal is just how to use this distributed timer quickly.

Not much to say, beginners understand beginners best

Official website and source code download address

Official website: https://www.xuxueli.com/xxl-job/
Source code download address: https://github.com/xuxueli/xxl-job/releases

Preparation

1. Download the source code

According to the aboveSource code download addressThe link goes in to download the source code and it’s done
. Use it under Windows to download this one.
After downloading the source code, unzip it.

2. IDEA import project

After importing it looks like this

It can be seen that the source code provided by the author is mainly divided into three modules

  • xxl-job-admin
  • xxl-job-core
  • xxl-job-executor-samples

Let’s take a look at xxl-job-adminthis

Data preparation must be done before starting this module

3. Data Preparation

Prepare the required tables first, and use the sql provided by the author directly here.

Copy sql and execute it in your own database

Modify the configuration file
and change it to the configuration of your own database (you can look at other configuration information, and there are also configurations such as modifying sending emails)

4. Log in to the task scheduling center

xxl-job-adminrun startup class

After the startup is complete, you can log in to see

Address: http://localhost:8080/xxl-job-admin

This is the way to go in, but you need an account and password

In fact, the account and password are in the sql that was run before

Account: adminPassword
: 123456

Enter account and password, log in

After logging in, you can see the control page of the task scheduling center.

You can click on this sidebar yourself and see what’s there

Now that the control platform has been opened, how do I add my scheduled tasks?

5. Test the scheduled task

Here the author provides xxl-job to integrate other frameworks or software. Here we first learn to integrate spring-boot. After all, this is the most important for java development.

It can be seen that the pom file in the project integrated with spring-boot has the dependency of introducing this xxl-job-core

<!-- xxl-job-core -->
<dependency>
    <groupId>com.xuxueli</groupId>
    <artifactId>xxl-job-core</artifactId>
    <version>${project.parent.version}</version>
</dependency>

So if we use this timer in our own project, we also need to add this dependency

The author also provides the docker configuration here, which can be used if you need to run on your own server

Let’s take a look at the configuration file of this project

The content of the configuration file is as follows:

# web port
server.port=8081
# no web
#spring.main.web-environment=false

# log config
logging.config=classpath:logback.xml

### xxl-job admin address list, such as "http://address" or "http://address01,http://address02" 
# This is mainly to configure the address of your task scheduling center (that is, the control platform) , if you start locally, you don't need to change it, otherwise change it to the address on your server 
xxl.job.admin.addresses =http:// 127.0 . 0.1 : 8080 /xxl-job-admin

### xxl-job, access token
xxl.job.accessToken=

### xxl-job executor appname 
xxl.job.executor.appname =xxl-job-executor-sample
 ### xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is null 
xxl .job.executor.address =
 ### xxl-job executor server-info 
xxl.job.executor.ip =
 # This is the port where your timer executes, I changed it to use the port that comes with the service, and then configure it Make an offset in the class, so that the port is better to maintain the point 
xxl.job.executor.port = ${server.port} 
#xxl.job.executor.port=9999 
### xxl-job executor log-path 
xxl. job.executor.logpath =/data/applogs/xxl-job/jobhandler
 ### xxl-job executor log-retention-days 
xxl.job.executor.logretentiondays = 30

Look at the configuration class again

The content is as follows:

@Configuration
public class XxlJobConfig {
    private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.accessToken}")
    private String accessToken;

    @Value("${xxl.job.executor.appname}")
    private String appname;

    @Value("${xxl.job.executor.address}")
    private String address;

    @Value("${xxl.job.executor.ip}")
    private String ip;

    @Value("${xxl.job.executor.port}")
    private int port;

    @Value("${xxl.job.executor.logpath}")
    private String logPath;

    @Value("${xxl.job.executor.logretentiondays}")
    private int logRetentionDays;


    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAppname(appname);
        xxlJobSpringExecutor.setAddress(address);
        xxlJobSpringExecutor.setIp(ip);
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setAccessToken(accessToken);
        xxlJobSpringExecutor.setLogPath(logPath);
        xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);

        return xxlJobSpringExecutor;
    }

}

Modify the actuator port offset (this depends on your own preferences, you can specify the port yourself, I directly add the service port and add 1000 to the actuator port)

If successful, then run the startup class of this xxl-job-executor-sample-springservice .

This timed task is xxl-job-executor-sample-springbootactually a task in , which can be found in the SampleXxlJob.javaclass

Then let’s execute this timer task.

Online Cron Expression Generator: https://cron.qqe2.com/

You can see that this is executed every day at 0:00 in the morning, this is not possible, then change it

Go and modify the demoJobHandlerscheduled , and print something for it to facilitate observation

Restart the project and clear the console

Start the scheduled task

When the point is reached, go to the console to see the execution

You can see that the console has six prints (because it is set to execute every 10 seconds starting at 11:35)

You can also query the log of this scheduled task

Integrate into your own project

Now it should be almost the same for how to use this xxl-job, and now I will integrate it into my own project

Adding modules to my own projectmike-xxl-job

The structure of the module is probably like this

I use the yml method for the configuration file here, and use [nacos to] manage my configuration. The following is the content of my various files

(The following content needs to be configured according to the project itself, for reference only)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>mike-parent</artifactId>
        <groupId>com.mike</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>mike-xxl-job</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.mike</groupId>
            <artifactId>mike-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!-- spring-boot-starter-web (spring-webmvc + tomcat) -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- xxl-job-core -->
        <dependency>
            <groupId>com.xuxueli</groupId>
            <artifactId>xxl-job-core</artifactId>
            <version>2.3.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <outputDirectory>${project.parent.basedir}/jars</outputDirectory>
                    <finalName>${project.artifactId}</finalName>
                    <mainClass>com.mike.mo.job.XxlJobApplication </ mainClass > 
                    < layout > ZIP </ layout > 
                </ configuration > 
                < executions > 
                    < execution > 
                        < goals > 
                            < goal > repackage </ goal > <!-- you can put dependencies Packages are packaged into the generated Jar package --> 
                        </ goals > 
                    </ execution > 
                </ executions > 
            </ plugin > 
        </ plugins > 
    </build>

</project>

application.yml

server:
  port: 6804
logging:
  config: classpath:logback.xml
  file: /www/mike/project-mike/logs/mike-xxl-job.log
  level:
    com.alibaba.nacos: error
spring:
  application:
    name: mike-xxl-job
  main:
    allow-bean-definition-overriding: true
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        namespace: f90ad91c-ac39-4a2d-8fb3-fcd33ded9123
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/duojiala?characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
    hikari:
      username: 'root'
      password: 'root'
      driver-class-name: 'com.mysql.cj.jdbc.Driver'
      max-lifetime: 120000

xxl-job:
  admin:
    addresses: http://127.0.0.1:8080/xxl-job-admin
  executor:
    appName: mike-xxl-job
    ip:
    port: ${server.port}
    logPath: /data/applogs/xxl-job/jobhandler
    logRetentionDays: 30
  accessToken:

bootstrap.yml

spring:
  application:
    name: mk-xxl-job
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yaml
        namespace: f90ad91c-ac39-4a2d-8fb3-fcd33ded9123
  profiles:
    active: local

logback.xml(This is directly copied from the author, and I have not studied it), and it is also glued below

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="1 seconds">

    <contextName>logback</contextName>
    <property />

    <appender >
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender >
        <file>${log.path}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="console"/>
        <appender-ref ref="file"/>
    </root>

</configuration>

XxlJobApplication.java

@SpringBootApplication
public class XxlJobApplication {
    public static void main(String[] args) {
        SpringApplication.run(XxlJobApplication.class,args);
    }
}

MikeXxlJob.java

@Component
public class MikeXxlJob {
    private final static Logger logger = LoggerFactory.getLogger(MikeXxlJob.class);

    /**
     * my first timer task
     */
    @XxlJob("funJobHandler")
    public void funJobHandler() {
        System.out.println( "Ah~ I executed~~~~" );
    }
}

I integrated the configuration of xxl-job into a bean object, which is a bit different from the previous propertiesconfiguration file

XxlJobBeanConfig.java

@Component
@ConfigurationProperties(prefix = "xxl-job")
@Data
public class XxlJobBeanConfig {
    private Admin admin;
    private Executor executor;
    private String accessToken;

    @Data
    public static class Executor {
        private String appName;
        private String ip;
        private int port;
        private String logPath;
        private int logRetentionDays;
    }

    @Data
    public static class Admin {
        private String addresses;
    }
}

XxlJobConfig.javaxxl-job timer configuration class

@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class XxlJobConfig {
    private final Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

    private final XxlJobBeanConfig bean;

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(bean.getAdmin().getAddresses());
        xxlJobSpringExecutor.setAppname(bean.getExecutor().getAppName());
        xxlJobSpringExecutor.setAddress(bean.getAdmin().getAddresses());
        xxlJobSpringExecutor.setIp(bean.getExecutor().getIp());
        xxlJobSpringExecutor.setPort(bean.getExecutor().getPort()+ 1000 ); //The port is offset backward by 1000
        xxlJobSpringExecutor.setAccessToken(bean.getAccessToken());
        xxlJobSpringExecutor.setLogPath(bean.getExecutor().getLogPath());
        xxlJobSpringExecutor.setLogRetentionDays(bean.getExecutor().getLogRetentionDays());

        return xxlJobSpringExecutor;
    }
}

The above is all the code of my timer module. Now let’s run mike-xxl-jobthe

Set the timing rules and start the newly added timing task

When the time is up, my scheduled task is also executed

View the scheduling log below

Summarize

This is the whole content of the xxl-job quick start, and some content has not been added. You can learn it by yourself. After I have some practical experience, I will do in-depth research and share it with you.

You may also like...

Leave a Reply

Your email address will not be published.