SpringBoot+ShedLock实现定时任务的分布式锁

废话不多说,直接上代码(概念的东西自己可以百度,后续考虑补上)

1.pom.xml


    
        1.8
        2.0.2.RELEASE
    
    
        
            
                org.springframework.boot
                spring-boot-dependencies
                ${springboot.version}
                pom
                import
            
        
    
    
        
            org.springframework.boot
            spring-boot-starter
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
            
        
        
            org.springframework.boot
            spring-boot-starter-log4j2
        
        
            com.github.ulisesbocchio
            jasypt-spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            net.javacrumbs.shedlock
            shedlock-spring
            2.1.0
        
        
            net.javacrumbs.shedlock
            shedlock-provider-jdbc-template
            2.3.0
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        
        
            mysql
            mysql-connector-java
            5.1.46
        
    

2.启动类


@SpringBootApplication
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
@EnableScheduling
@MapperScan({"com.yw.mapper"})
@EnableAsync
public class SalaryApplication {
	public static void main(String[] args) {
		SpringApplication.run(SalaryApplication.class, args);
	}
}

3.配置类config

@Configuration
public class ScheduledLockConfig {

    @Bean
    public LockProvider lockProvider(DataSource dataSource){
        return new JdbcTemplateLockProvider(dataSource);
    }
}

4.定时任务

@Component
public class ScheduledTask {

	private static AtomicInteger atomicInteger=new AtomicInteger(0);

	@Scheduled(cron = "0/5 * * * * *")
	@SchedulerLock(name = "scheduledTask", lockAtLeastFor = 5000, lockAtMostFor = 10000)
	public void scheduledTask() {
		int res = atomicInteger.addAndGet(1);
		System.out.println("res = " + res);
	}
}

5.application.properties

server.port=8020
spring.application.name=helloword
mybatis.mapper-locations=classpath:mapper/*.xml

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

6.数据库,建表

CREATE TABLE `shedlock` (
  `name` varchar(64) NOT NULL,
  `lock_until` timestamp(3) NULL DEFAULT NULL,
  `locked_at` timestamp(3) NULL DEFAULT NULL,
  `locked_by` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

7.修改application.properties的端口为8020,8021,8022,分别启动三个application,每5秒钟只能有一个服务执行成功。

 

你可能感兴趣的:(微服务)