java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot CronJob定时任务

k8s+springboot+CronJob定时任务部署实现

作者:xiaogg3678

本文主要介绍了k8s+springboot+CronJob定时任务部署实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

kubernetes+springboot+CronJob 定时任务配置如下代码:

cronjob.yaml k8s 文件  

apiVersion: batch/v1
kind: CronJob
metadata:
  name: k8s-springboot-demo
  namespace: rz-dt
spec:
  failedJobsHistoryLimit: 3 #执行失败job任务保留数量
  successfulJobsHistoryLimit: 5 #执行成功job任务保留数量
  startingDeadlineSeconds: 180
  concurrencyPolicy: Forbid
  schedule: "*/1 * * * *" #每分钟执行一次
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: k8s-springboot-demo
              image: rz-dt-image-server-registry-vpc.cn-shanghai.cr.aliyuncs.com/rz-dt/k8s-springboot-demo:$IMG_TAG
              imagePullPolicy: Always
              #command: ["java","-jar","/usr/local/cenobitor/k8s-springboot-demo.jar"]#dockerfile已有此处不需要配置
              args: ["sendEmail","sendEmail2"] # 配置任务类的名称
              volumeMounts:
                - name: time-config
                  mountPath: /etc/localtime
                  readOnly: true
              #envFrom:
              # - configMapRef:
              #      name: smcp-config
              # - secretRef:
              #     name: smcp-service-secret
              resources:
                requests:
                  cpu: "250m"
                  memory: 216Mi
                limits:
                  cpu: "500m"
                  memory: 512Mi
          restartPolicy: Never
          #从私有仓库拉取镜像凭证
          imagePullSecrets:
            - name: rz-dt-miyue-vpc
          volumes:
            - name: time-config
              hostPath:
                path: /usr/share/zoneinfo/Asia/Shanghai

Dockerfile 文件

#基础镜像,如果本地仓库没有,会从远程仓库拉取 openjdk:8
FROM openjdk:8
#暴露端口
EXPOSE 8089
#容器中创建目录
RUN mkdir -p /usr/local/cenobitor
#编译后的jar包copy到容器中创建到目录内
COPY target/k8s-springboot-demo.jar /usr/local/cenobitor/k8s-springboot-demo.jar
#指定容器启动时要执行的命令
ENTRYPOINT ["java","-jar","/usr/local/cenobitor/k8s-springboot-demo.jar"]

test.sh 文件

echo "开始制作镜像..."
image_tag=`date +%Y-%m-%d-%H-%M-%S` #_%H%M
echo "当前时间:$image_tag"
docker build -t k8s-springboot-demo:${image_tag} .
echo "制作镜像成功!"
echo "登录"
sudo docker login --username=aliyun0398513152 rz-dt-image-server-registry-vpc.cn-shanghai.cr.aliyuncs.com --password=1234
echo "镜像最新版本提交"
docker tag k8s-springboot-demo:${image_tag} rz-dt-image-server-registry-vpc.cn-shanghai.cr.aliyuncs.com/rz-dt/k8s-springboot-demo:${image_tag}
docker push rz-dt-image-server-registry-vpc.cn-shanghai.cr.aliyuncs.com/rz-dt/k8s-springboot-demo:${image_tag}
echo "k8s一键部署"
export IMG_TAG=${image_tag}
envsubst < cronjob.yaml | kubectl --kubeconfig ~/.kube-rz/config apply -f -
 

4个代码实现类:

package com.example.demo.job;
public interface Command {
    /**
     * 遵循Unix约定,如果命令执行正常,则返回0;否则为非0。
     */
    int execute(String... args);
}
package com.example.demo.job;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class SendEmailCommand implements Command {
    @Override
    public int execute(String... args) {
        try {
            // 省略业务逻辑代码
            for (String arg:args) {
                log.info("send email  success args:" +arg);
            }
            log.info("send email success");
            return 0;
        } catch (Exception e) {
            log.error("send email error", e);
            return -1;
        }
    }
}
package com.example.demo.job;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class SendEmail2Command implements Command {
    @Override
    public int execute(String... args) {
        try {
            // 省略业务逻辑代码
            for (String arg:args) {
                log.info("send email 2  success args:" +arg);
            }
            log.info("send email 2 success");
            return 0;
        } catch (Exception e) {
            log.error("send email error", e);
            return -1;
        }
    }
}
package com.example.demo.job;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Component
@Slf4j
public class ProjectCommandLineRunner implements CommandLineRunner {
    Map<String, Command> commandMap = new HashMap<>();
    @Autowired
    private SendEmailCommand sendEmailCommand;
    @Autowired
    private SendEmail2Command sendEmail2Command;
    @PostConstruct
    private void init() {
        commandMap.put("sendEmail", sendEmailCommand);
        commandMap.put("sendEmail2", sendEmail2Command);
    }
    @Override
    public void run(String... args) throws Exception {
        if (args.length == 0) {
            return;
        }
        if (!commandMap.containsKey(args[0])) {
            log.error("'{}' command not found", args[0]);
            System.exit(-1);
        }
        for (String arg:args) {
            log.info("command args:" +arg);
        }
       for (int i = 0; i < args.length; i++) {
            Command command =  commandMap.get(args[i]);
            String[] arguments = Arrays.copyOfRange(args, 0, args.length);
            command.execute(arguments);
        }
        //执行成功则,正常退出0, 异常退出非0
        System.exit(0);
    }
}
 

kubectl 客户端执行,sh test.sh :

到此这篇关于k8s+springboot+CronJob定时任务部署实现的文章就介绍到这了,更多相关springboot CronJob定时任务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文