【Mybatis-Plus租户id结合定时任务 @Scheduled】

文章目录

  • 前言
  • 一、启动类加上@EnableScheduling、@EnableAsync
  • 二、创建定时任务类
  • 3、多线程环境下配置多线程配置
  • 4、以下是一个示例代码,展示了如何在Mybatis-Plus中配置租户解析器,以便在定时任务中使用:
  • 5、有可能会报没有线程绑定错误,添加一个线程绑定就可以了。


前言

提示:这里可以添加本文要记录的大概内容:

例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:以下是本篇文章正文内容,下面案例可供参考

一、启动类加上@EnableScheduling、@EnableAsync

二、创建定时任务类

package com.jsh.erp.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jsh.erp.datasource.entities.project.ProTask;
import com.jsh.erp.datasource.mappers.project.ProTaskMapper;
import com.jsh.erp.service.project.ProTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;

@Component
@Slf4j
@Async
public class TaskOutTime {

   @Autowired
   private ProTaskService proTaskService;

   /*@Autowired
   private Executor taskTimeOutExecutor;

   @Autowired
   private ProTaskMapper proTaskMapper;*/

//   @Scheduled(cron = "0 0 0 * * ?")
   @Scheduled(cron = "0/2 * * * * ?")
   public void proTaskTimeOut(){

      Date date = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      String date1 = sdf.format(date);
      log.info("date1"+date1);
      LambdaQueryWrapper<ProTask> proTaskLambdaQueryWrapper = new LambdaQueryWrapper<>();
      proTaskLambdaQueryWrapper.eq(ProTask::getEndDate,date1);
      List<ProTask> proTaskList = proTaskService.list(proTaskLambdaQueryWrapper);
      for (ProTask proTask : proTaskList) {
         proTask.setState(4);
         proTaskService.updateById(proTask);
      }


      /*taskTimeOutExecutor.execute(() -> {
         // 在新的线程中执行的任务
         Date date = new Date();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         String date1 = sdf.format(date);
         log.info("date1"+date1);
         LambdaQueryWrapper proTaskLambdaQueryWrapper = new LambdaQueryWrapper<>();
         proTaskLambdaQueryWrapper.eq(ProTask::getEndDate,date1);
         List proTaskList = proTaskService.list(proTaskLambdaQueryWrapper);
         for (ProTask proTask : proTaskList) {
            proTask.setState(4);
            proTaskService.updateById(proTask);
         }
      });*/
   }
}

3、多线程环境下配置多线程配置

package com.jsh.erp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
@Configuration
public class TimerTaskConfig {
    @Bean
    public Executor taskTimeOutExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(30);
        executor.setThreadNamePrefix("MyTaskExecutor-");
        executor.initialize();
        return executor;
    }
}

4、以下是一个示例代码,展示了如何在Mybatis-Plus中配置租户解析器,以便在定时任务中使用:

public PaginationInterceptor paginationInterceptor(HttpServletRequest request) {
    PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
    List<ISqlParser> sqlParserList = new ArrayList<>();
    TenantSqlParser tenantSqlParser = new TenantSqlParser();
    tenantSqlParser.setTenantHandler(new TenantHandler() {
        @Override
        public Expression getTenantId() {
            String token = request.getHeader("X-Access-Token");
            Long tenantId = Tools.getTenantIdByToken(token);
            if (tenantId != 0L) {
                return new LongValue(tenantId);
            } else {
                //超管
                return null;
            }
        }
        @Override
        public String getTenantIdColumn() {
            return "tenant_id";
        }
        @Override
        public boolean doTableFilter(String tableName) {
            if ("t_xxxx".equals(tableName)) {//你要过滤的表名
                return true;
            }
        });
}

其中,getTenantId()方法从请求中获取租户ID,并返回一个LongValue对象;getTenantIdColumn()方法返回租户ID所在的列名;doTableFilter()方法用于过滤不需要使用租户ID的表。

或者

package com.jsh.erp.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.jsh.erp.utils.Tools;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
@Configuration
public class TimerTaskConfig {
    @Bean
    public Executor taskTimeOutExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(30);
        executor.setThreadNamePrefix("MyTaskExecutor-");
        executor.initialize();
        return executor;
    }

    public PaginationInterceptor paginationInterceptor(HttpServletRequest request) {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        List<ISqlParser> sqlParserList = new ArrayList<>();
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
        tenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
            public Expression getTenantId() {
                String token = request.getHeader("X-Access-Token");
                Long tenantId = Tools.getTenantIdByToken(token);
                if (tenantId != 0L) {
                    return new LongValue(tenantId);
                } else {
                    //超管
                    return null;
                }
            }
            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }
            @Override
            public boolean doTableFilter(String tableName) {
                if ("t_xxxx".equals(tableName)) {//你要过滤的表名
                    return true;
                }
                return false;
            }
            });
        return null;
        }

    }

5、有可能会报没有线程绑定错误,添加一个线程绑定就可以了。

package com.jsh.erp.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jsh.erp.datasource.entities.project.ProTask;
import com.jsh.erp.datasource.mappers.project.ProTaskMapper;
import com.jsh.erp.service.project.ProTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * 定时任务
 */

@Component
@Slf4j
@Async
public class TaskOutTime {

   @Autowired
   private ProTaskService proTaskService;

   /*@Autowired
   private Executor taskTimeOutExecutor;

   @Autowired
   private ProTaskMapper proTaskMapper;*/



//   @Scheduled(cron = "0 0 0 * * ?")
   @Scheduled(cron = "0/2 * * * * ?")
   public void proTaskTimeOut(){

      /**
       * 添加一个线程绑定
       */
      RequestAttributes obj = RequestContextHolder.getRequestAttributes();
      if(obj==null){
         obj = new ServletRequestAttributes(new MockHttpServletRequest());
      }
      RequestContextHolder.setRequestAttributes(obj);

      Date date = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      String date1 = sdf.format(date);
      log.info("date1"+date1);
      LambdaQueryWrapper<ProTask> proTaskLambdaQueryWrapper = new LambdaQueryWrapper<>();
      proTaskLambdaQueryWrapper.eq(ProTask::getEndDate,date1);
      List<ProTask> proTaskList = proTaskService.list(proTaskLambdaQueryWrapper);
      for (ProTask proTask : proTaskList) {
         proTask.setState(4);
         proTaskService.updateById(proTask);
      }


      /*taskTimeOutExecutor.execute(() -> {
         // 在新的线程中执行的任务
         Date date = new Date();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         String date1 = sdf.format(date);
         log.info("date1"+date1);
         LambdaQueryWrapper proTaskLambdaQueryWrapper = new LambdaQueryWrapper<>();
         proTaskLambdaQueryWrapper.eq(ProTask::getEndDate,date1);
         List proTaskList = proTaskService.list(proTaskLambdaQueryWrapper);
         for (ProTask proTask : proTaskList) {
            proTask.setState(4);
            proTaskService.updateById(proTask);
         }
      });*/
   }
}

你可能感兴趣的:(mybatis)