kubernetes+springboot+CronJob 定时任务配置如下代码:
- cronjob.yaml k8s 文件
apiVersion: batch/v1 kind: CronJob metadata:name: k8s-springboot-demonamespace: rz-dt spec:failedJobsHistoryLimit: 3 #执行失败job任务保留数量successfulJobsHistoryLimit: 5 #执行成功job任务保留数量startingDeadlineSeconds: 180concurrencyPolicy: Forbidschedule: "*/1 * * * *" #每分钟执行一次jobTemplate:spec:template:spec:containers:- name: k8s-springboot-demoimage: rz-dt-image-server-registry-vpc.cn-shanghai.cr.aliyuncs.com/rz-dt/k8s-springboot-demo:$IMG_TAGimagePullPolicy: Always#command: ["java","-jar","/usr/local/cenobitor/k8s-springboot-demo.jar"]#dockerfile已有此处不需要配置args: ["sendEmail","sendEmail2"] # 配置任务类的名称volumeMounts:- name: time-configmountPath: /etc/localtimereadOnly: true#envFrom:# - configMapRef:# name: smcp-config# - secretRef:# name: smcp-service-secretresources:requests:cpu: "250m"memory: 216Milimits:cpu: "500m"memory: 512MirestartPolicy: Never#从私有仓库拉取镜像凭证imagePullSecrets:- name: rz-dt-miyue-vpcvolumes:- name: time-confighostPath: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=1234echo "镜像最新版本提交" 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 {@Overridepublic 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 {@Overridepublic 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<>();@Autowiredprivate SendEmailCommand sendEmailCommand;@Autowiredprivate SendEmail2Command sendEmail2Command;@PostConstructprivate void init() {commandMap.put("sendEmail", sendEmailCommand);commandMap.put("sendEmail2", sendEmail2Command);}@Overridepublic 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, 异常退出非0System.exit(0);} }
kubectl 客户端执行,sh test.sh :