springboot配置
springboot基本已整合所有,此处只是对默认配置的修改以及配置一些环境
1.配置Mybatis
首先引入场景mybatis启动器以及mysql依赖等:数据库连接池默认使用的是hikari连接池,无需做其他配置,即可使用。当然如果想要更换为德鲁伊,只需更改type就可以了,前提是引入Druid的启动器
org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 mysql mysql-connector-java com.alibaba druid-spring-boot-starter 1.1.22
mybatis:
//扫描映射文件.xml文件,具体看你的映射文件位置,可以指定别名包。
mapper-locations: classpath:com/javasm/*/mapper/*.xml
type-aliases-package: com.javasm
spring:
datasource:
//springboot默认用的驱动是8.0.22(2.4.2版本)时区必须加上GMT+8
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource//默认是hikari连接池(可以不用指定type),此处修改为德鲁伊(指定type为druid),还有一些其他配置可以酌情配置initial-size、max-active等
注意:在启动类上不要忘记配置接口扫描注解,@MapperScan("接口所在位置")
2.静态资源配置
静态资源包括css、js、图片、以及html等。默认客户端是不能进行直接访问,相当于以前的webapps目录下的WEB-INF目录下的文件,只能通过前端控制器进行访问,springboot内部默认加载4个静态资源目录:["/META-INF/resources","/resources/","/static/","/public/"],
@Configuration public class MyCommonConfig { @Bean//跨域配置 public FilterRegistrationBeancorsFilter(){ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("http://localhost:8888"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**",config); FilterRegistrationBean bean = new FilterRegistrationBean<>(new org.springframework.web.filter.CorsFilter(source)); bean.setOrder(0); return bean; } }
4.配置拦截器
新建一个类 implements WebMvcConfigurer
@Component public class MyWebMvcConfig implements WebMvcConfigurer { @Resource //首先自定义一个拦截器,然后将其将其放入容器@Component,然后在此处装配。 LoginInterceptor loginInterceptor; @Override //alt+insert复写此方法,配置需要拦截的资源,以及需要放行的资源 public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/login","/css/**")
; } }
5.日志集成
springboot默认使用logback日志组件,可以自己进行修改日志组件,此处修改为log4j2日志组件,引入启动器,排除web启动器中的logging依赖
org.springframework.boot spring-boot-starter-log4j2
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-logging
将log4j2的配置文件log4j2.xml直接放在resources目录下即可
6.事务支持以及分页插件
在启动类上开启事务支持,@EnableTransactionManagement,然后在service层配置@Transactional注解使用。
@SpringBootApplication(scanBasePackages = "com.javasm")//包扫描,与SSM中的ComponentScan作用相同,默认是扫描启动类所在的包以及其所在包下的所有子包,此处手动配置为com.javasm @MapperScan("com.javasm.*.mapper")//扫描dao层接口,动态代理此接口并放入容器中, @EnableTransactionManagement//开启事务支持 public class Boot01Application { public static void main(String[] args) { SpringApplication.run(Boot01Application.class, args); } }
添加分页启动器,pagehelper-spring-boot-starter,与以前一样使用即可
PageHelper.startPage(pageNum,pageSize); Listall = sysuserService.all(); PageInfo list = new PageInfo<>(all);
//注册线程池 @Bean public ThreadPoolTaskExecutor createTaskExecutor(){ ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(5); threadPoolTaskExecutor.setMaxPoolSize(10); threadPoolTaskExecutor.setQueueCapacity(100); threadPoolTaskExecutor.setKeepAliveSeconds(40); threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); threadPoolTaskExecutor.initialize(); return threadPoolTaskExecutor; }
在启动类上开启异步任务注解,@EnableAsync开启异步任务,然后在service层要执行的异步方法上配合使用@Async注解,如下例:
//控制层方法,调用service层中的异步方法。
@GetMapping("sendSms") public String sendSms(){ System.out.println("主线程:"+Thread.currentThread().getName()); sysuserService.sendSms(); System.out.println("主线程:"+Thread.currentThread().getName()); return "hello"; }
//这个是service层方法,使用Asnc注解,标明此方法是一个异步方法, @Async @Override public void sendSms() { System.out.println("异步发短信:123456789--"+Thread.currentThread().getName()); }
执行结果如下:
主线程:http-nio-8080-exec-1
主线程:http-nio-8080-exec-1
异步发短信:123456789--createTaskExecutor-1
定时任务:在服务器启动后,在后台默认按照指定时间策略重复执行的任务。此处使用spring-task,首先在启动类上开启任务调度 @EnableScheduling,然后在任务类中的方法上添加@scheduled注解
//开启两个定时任务
@Scheduled(cron = "0/5 * * * * ?") public void test01(){ System.out.println("每隔⑤秒执行一次"); } @Scheduled(cron = "0/7 * * * * ?") public void test02(){ System.out.println("每隔⑦秒执行一次"); }
执行结果,
每隔⑤秒执行一次
每隔⑤秒执行一次
每隔⑦秒执行一次
每隔⑤秒执行一次
每隔⑦秒执行一次
每隔⑤秒执行一次
每隔⑦秒执行一次
每隔⑤秒执行一次
注意:springboot默认spring.task.scheduling.pool.size值为1,所以也就是单线程的,如果多个任务调度同时执行,并且其中有比较耗时的任务时,其他任务就会等待被阻塞直到该任务执行完成,可以在yml配置文件中配置线程数量
spring:
task:
scheduling:
pool:
size: 5
8.redis数据库
SpringBoot2.0默认采用Lettuce客户端来连接Redis服务端的,此处使用jedis来使用,首先引入场景启动器,排除默认的lecttuce,引入jedis依赖
org.springframework.boot spring-boot-starter-data-redis io.lettuce lettuce-core redis.clients jedis
配置连接池(单机配置)
redis: host: 127.0.0.1 port: 6379 password: root jedis: pool: max-active: 8 max-idle: 8 max-wait: 300
-
StringRedisTemplate对象,要求手工把对象转json字符串。
-
RedisTemplate对象,该对象内使用Jdk的对象流进行序列化,数据不好管理。一般会自定义RedisTemplate对象注册到容器中,指定key与value的序列化方式。
以下为redis自动配置的源码,由于不够灵活,一般会自定义RedisTemplate对象注册到容器中,指定key与value的序列化方式
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")//默认生效,手动指定RedisTemplate的bean可让其失效,改为我们手动指定的序列化方式
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate
在配置类中配置如下Bean对象,手动指定RedisTemplate的name属性@Bean(name = "redisTemplate")让默认的RedisTemplate失效
@Bean(name = "redisTemplate") public RedisTemplateredisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; }