springboot2 集成 shedlock 4
首先可以通过文档了解shedlock的一些信息https://github.com/lukas-krecan/ShedLock1. 引入依赖....<properties><shedlock.version>4.19.1</shedlock.version></properties><!-- shedlock --><depende
·
首先可以通过文档了解shedlock的一些信息 https://github.com/lukas-krecan/ShedLock
1. 引入依赖
....
<properties>
<shedlock.version>4.19.1</shedlock.version>
</properties>
<!-- shedlock -->
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>${shedlock.version}</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-jdbc-template</artifactId>
<version>${shedlock.version}</version>
</dependency>
2.执行sql语句,通过外部进程提供锁
# MySQL, MariaDB
CREATE TABLE shedlock(name VARCHAR(64) NOT NULL, lock_until TIMESTAMP(3) NOT NULL,
locked_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), locked_by VARCHAR(255) NOT NULL, PRIMARY KEY (name));
3. 编写配置
package zyy.demo.seckill.config;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import zyy.demo.seckill.utils.TimeUtil;
import javax.sql.DataSource;
import java.time.LocalDateTime;
import java.util.TimeZone;
/**
* @author zyy
* @program seckill
* @description ${}
* @date 2020-12-30 10:21
**/
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT5M")
public class SchedulerConfig {
@Scheduled(cron = "0/1 * * * * ? ")
@SchedulerLock(name = "printTime", lockAtMostFor = "3s", lockAtLeastFor = "2s")
public void scheduledTask() {
/**
通过设置lockAtMostFor,我们可以确保即使节点死亡,锁也会被释放;通过设置lockleast for,
我们可以确保它在5秒内不会执行超过一次。请注意,lockAtMostFor只是一个安全网,
以防执行任务的节点死亡,所以将它设置为一个明显大于最大估计执行时间的时间。
如果任务花费的时间比lockAtMostFor长,它可能会被再次执行,结果将是不可预测的(更多的进程将持有锁)。
* */
String s = TimeUtil.formatTime(LocalDateTime.now());
System.out.println(s);
}
@Scheduled(cron = "0/5 * * * * ? ")
@SchedulerLock(name = "printTime2", lockAtMostFor = "10s", lockAtLeastFor = "8s")
public void scheduledTask2() {
String s = TimeUtil.formatTime(LocalDateTime.now());
System.err.println(s);
}
// ---------------------------------------------配置锁提供程序——通过外部进程提供锁,如SQL数据库、Mongo、Redis等
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(
JdbcTemplateLockProvider.Configuration.builder()
.withJdbcTemplate(new JdbcTemplate(dataSource))
.withTimeZone(TimeZone.getTimeZone("Asia/Shanghai"))
.build()
);
}
}
4.查看数据库
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)