SpringBoot 任务调度(立即启动、周期启动)、 Servlet应用、总结day-05

SpringBoot 任务调度

       在很多系统中,经常会遇到定时、周期调用一个或多个任务。 SpringBoot提供了Job Schedule模块,可以方便的开发任务调用功能。原来企业一般都采用quartz工具实现。

服务器启动立刻执行

服务器启动-->加载项目project-->web.xml-->servlet、filter、listener-->任务写到构造器或init初始化方法中

SpringBoot提供了ApplicationRunner和CommandLineRunner接口,用于实现启动服务器后自动执行任务。

web.xml:

<dependencies>
  	<dependency>
  		<groupId>org.springframework.boot</groupId>
  		<artifactId>spring-boot-starter-web</artifactId>
  		<version>2.0.1.RELEASE</version>
  	</dependency>
  </dependencies>

启动类:

@SpringBootApplication
public class MyBootApplication {

	public static void main(String[] args) {
		SpringApplication.run(MyBootApplication.class, args);
	}

}

设置服务器端口号:

server.port=8888

1.实现ApplicationRunner

@Component
@Order(1)
public class MyTask1 implements ApplicationRunner{

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("启动服务器立刻执行任务1"+new Date());
    }

}

2.实现CommandLineRunner

@Component
@Order(2)
public class MyTask2 implements CommandLineRunner{

    @Override
    public void run(String... args) throws Exception {
        System.out.println("启动服务器立刻执行任务2"+new Date());

    }

}

运行结果:

注意事项:@Order(1)这个标签是用于控制默认启动的先后顺序的。如果order标签中数字顺序相同则根据类名系统自动分配顺序。

且通过sleep()函数可以测试出默认启动的任务是用的同一个线程,一个任务没结束睡眠另一个自动启动的任务会等待。

应用案例:把spring访问mybatis 和 访问redis结合实现服务器启动就将mybatis中DEPT表的数据缓存到Redis数据库

引入工作依赖包

配置信息

server.port=8888

spring.datasource.username=scott
spring.datasource.password=123456
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:MLDN
spring.datasource.driverClassName=oracle.jdbc.OracleDriver

spring.redis.host=localhost
spring.redis.port=6379

编写实体类

public class Dept implements Serializable{
	private Integer deptno;
	private String dname;
	private String loc;
	public Integer getDeptno() {
		return deptno;
	}
	public void setDeptno(Integer deptno) {
		this.deptno = deptno;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	
}

编写Dao接口

public interface DeptDao {
	
	@Select("select * from dept")
	public List<Dept> findAll();
}

随服务器启动的任务调度

@Component
public class MyTask3 implements ApplicationRunner{
	@Autowired
	private DeptDao deptDao;
	
	@Autowired
	private RedisTemplate<Object, Object> redis;
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println("执行任务,将DEPT表内容缓存到Redis");
		List<Dept> list = deptDao.findAll();
		redis.opsForValue().set("depts", list);
	}

}

主启动类

@SpringBootApplication
@MapperScan(basePackages={"cn.xdl.dao"})
public class MyBootApplication {

	public static void main(String[] args) {
		SpringApplication.run(MyBootApplication.class, args);
	}
	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory){
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(factory);
		template.setKeySerializer(new StringRedisSerializer());
		return template;
	}
}

结果:运行主启动类,自动实现dao接口中的方法查找所有DEPT表中数据,缓存到Redis

定时周期性自动执行

@Component
@EnableScheduling
public class MyTask4 {

    @Scheduled(cron="3/10 * * * * ?")
    public void run(){
        System.out.println("周期性执行任务4"+new Date());
    }

}

Cron表达式参考下面资料

https://www.cnblogs.com/yanghj010/p/10875151.html

SpringBoot Servlet应用

1.编写Servlet组件,使用@WebServlet配置

@WebServlet(name="helloservlet",loadOnStartup=1,urlPatterns={"/hello","/hello.do"})
public class HelloServlet extends HttpServlet{

    public void service(HttpServletRequest request,
        HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("Hello SpringBoot");
        out.close();
    }

}

2.编写Filter组件,使用@WebFilter配置

//@WebFilter(displayName="myfilter",urlPatterns={"/hello","/hello.do"})
@WebFilter(filterName="myfilter",servletNames={"helloservlet"})
public class MyFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, 
        ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("执行了MyFilter过滤器");
        chain.doFilter(request, response);//放过
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}

3.定义启动类,追加@ServletComponentScan

@SpringBootApplication
@ServletComponentScan//扫描Servlet组件,@WebServlet、@WebFilter、@WebListener
public class MyBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyBootApplication.class, args);
    }

}

提示:多个Filter执行顺序按类名字典顺序执行。

运行:http://localhost:8888/hello.dohttp://localhost:8888/hello

后太打印执行的过滤器信息:

SpringBoot 总结

SpringBoot是对Spring框架进行封装,快速搭建和开发Spring应用。

Spring IOC 

   IOC: 组件管理、对象关系注入

   Spring框架:<bean> 和<context:component-scan>

SpringBoot的beans定义、自动配置、组件扫描

SpringBoot 连接池

(工具集)spring-boot-starter-jdbc工具集、驱动包

 自动配置连接池,spring-boot-starter-jdbc 内置hikar连接池

 指定其他的,可以使用spring.datasource.type或使用@Bean自定义

SpringBoot 数据库访问

(工具集)spring-boot-starter-jdbc、mybatis-spring-boot-starter、spring-boot-starter-jpa、

spring-boot-starter-data-redis、spring-boot-starter-data-mongodb、驱动包

  Spring DAO:注入JdbcTemplate、自定义DAO组件

  Spring+Mybatis:实体类、Mapper映射器、主启动类加上@MapperScan  

  Spring+JPA:实体类/映射描述、Dao接口(继承JpaRepository)

  Redis: 注入RedisTemplate

  MongoDB:注入MongoTemplate

SpringBoot MVC

spring-boot-starter-web工具

  开发restful服务(发出rest请求返回json结果)

  开发Thymeleaf应用(发送请求返回HTML结果)

  开发JSP应用(发送请求返回HTML结果)

  静态资源管理和访问(public、static、resources、META-INF/resources、自定义)

  springMVC拦截器(定义拦截器、配置WebMvcConfigurer)

  Spring异常处理(BasicErrorController、自定义ErrorController、@ExceptionHandler)

Spring AOP

spring-boot-starter-aop

  编写切面组件,使用下面注解配置

  @Aspect、@Before、@After、@Aournd、@AfterThrowing、@AfterReturning

Spring 任务调度

  服务器启动后立刻调用:ApplicationRunner或CommandLineRuuner

  服务器启动后周期性调用:@Scheduled、@EnableScheduling、cron表达式

SpringBoot整合Serclet、Filter、Listener

  定义Servlet、Filter、Listener组件

  配置@WebServlet、@WebFilter、@WebListener、@ServletCompomentScan
 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值