我们为什么要使用springboot?
相比于传统的Jave EE开发,springboot有如下几点优点:
1.遵循“约定优先于配置”,目标实现零配置。基本上我们只需要很少的配置,大部分我们都可以使用它默认配置
2.项目快速搭建,可以无配置整合第三方框架
3.应用内嵌应用服务器,新项目也可以快速启动,同时应用还支持jar包启动,不需要依赖外部应用服务器。
4.运行中应用的监控
springboot它强大背后的实现原理?
springboot加载原理
这边只是简单介绍springboot自动装备模块。
应用程序入口 @SpringBootApplication
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
Class>[] exclude() default {};
String[] excludeName() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackages"
)
String[] scanBasePackages() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackageClasses"
)
Class>[] scanBasePackageClasses() default {};
}
这边只介绍@EnableAutoConfiguration
自动配置幕后英雄:SpringFactoriesLoader详解
SpringFactoriesLoader属于Spring框架私有的一种扩展方案,主要功能就是从META-INF/spring.factories加载配置。配合@EnableAutoConfiguration使用的话,它更多是提供一种配置查找的功能支持,即根据@EnableAutoConfiguration的完整类名org.springframework.boot.autoconfigure.EnableAutoConfiguration作为查找的Key,获取对应的一组@Configuration类,实例化为对应的标注了@Configuration的JavaConfig形式的IoC容器配置类,然后汇总为一个并加载到IoC容器。
springboot支持哪些强大的模块或功能?
1.支持多环境配置
主配置application.properties 一般是不同环境不变的配置,dev等是各自特有的配置,加载顺序是先加载主配置,然后加载不同环境的配置,后者会覆盖前者配置
application.properties
application-dev.properties
application-test.properties
application-prod.properties
如何选择某个环境
1.spring.profiles.active=dev 主配置选择生效配置
2.java -jar application.jar --spring.profiles.active=dev 运行时添加参数配置
2.支持filter、servlet、listener
@ServletComponentScan
@SpringBootApplication
public class SpringBootDemo101Application {
}
@WebFilter(filterName = "customFilter", urlPatterns = "/*")
public class CustomFilter implements Filter {
}
@WebListener
public class CustomListener implements ServletContextListener {
}
@WebServlet(name = "customServlet", urlPatterns = "/user")
public class CustomServlet extends HttpServlet {
}
3.支持CORS跨域请求
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class ApiController {
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/get")
public HashMap get(@RequestParam String name) {
HashMap map = new HashMap();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}
4.支持关系型数据库JPA
引入spring-boot-starter-data-jpa模块
application.properties增加如下配置
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# JPA
spring.jpa.hibernate.ddl-auto= update
spring.jpa.show-sql=true
代码支持hql语句,还支持各种已定义格式语句
public interface UserLogDao extends JpaRepository {
/**
* @param string
* @return
*/
@Query(value = "select u from RoncooUserLog u where u.userName=?1")
List findByUserName(String userName);
}
5.支持mybatis
引入org.mybatis.spring.boot模块
application.properties增加配置如下
spring.datasource.url=jdbc:mysql://localhost/spring_boot_demo?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis
mybatis.mapper-locations: classpath:mybatis/*.xml
代码
@Mapper
public interface RoncooUserLogMapper {
}
配置文件省略
6.支持ehcache缓存
引入spring-boot-starter-cache、ehcache模块
application.properties 增加配置如下
spring.cache.ehcache.config=classpath:config/ehcache.xml
ehcache.xml配置如下
代码
@CacheConfig(cacheNames = "cache")
@Repository
public class UserLogCacheImpl implements UserLogCache {
@Autowired
private UserLogDao userLogDao;
@Cacheable(key = "#p0")
@Override
public UserLog selectById(Integer id) {
System.out.println("查询功能,缓存找不到,直接读库, id=" + id);
return userLogDao.findOne(id);
}
@CachePut(key = "#p0.id")
@Override
public UserLog updateById(UserLog userLog) {
System.out.println("更新功能,更新缓存,直接写库, id=" + roncooUserLog);
return userLogDao.save(userLog);
}
@Override
@CacheEvict
public String deleteById(Integer id) {
System.out.println("删除功能,删除缓存,直接写库, id=" + id);
return "清空缓存成功";
}
}
ps:@CachePut(key = "#p0") key支持el表达式,其中p0表示第一个参数,value默认为@CacheConfig的值
7.支持redis缓存
引入spring-boot-starter-data-redis模块
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=123456
#spring.redis.database=0
#spring.redis.pool.max-active=8
#spring.redis.pool.max-idle=8
#spring.redis.pool.max-wait=-1
#spring.redis.pool.min-idle=0
#spring.redis.timeout=0
#如果项目中引入了ehcache,这边需要设置
spring.cache.type=redis
代码
@Configuration
public class RedisCacheConfiguration extends CachingConfigurerSupport {
/**
* 自定义缓存管理器.
*
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate, ?> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// 设置默认的过期时间
cacheManager.setDefaultExpiration(20);
Map expires = new HashMap();
// 单独设置
expires.put("cache", 200L);
cacheManager.setExpires(expires);
return cacheManager;
}
/**
* 自定义key. 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。
*/
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* RedisTemplate配置
*/
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
8.支持rabbitmq等amqp
引入spring-boot-starter-amqp模块
application.properties增加如下配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.password=
spring.rabbitmq.username=
@Configuration
public class AmqpConfiguration {
@Bean
public Queue queueMessage() {
return new Queue("topic.message");
}
@Bean
TopicExchange exchange() {
return new TopicExchange("exchange");
}
/**
* 消费者设置队列binding_key绑定到exchanage
* @param queueMessages
* @param exchange
* @return
*/
@Bean
Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");
}
}
生产者 设置发送消息的routing_key
@Component
public class TopicSender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String msg1 = "I am topic.mesaage msg======";
System.out.println("sender1 : " + msg1);
this.rabbitTemplate.convertAndSend("exchange", "topic.message", msg1);
String msg2 = "I am topic.mesaages msg########";
System.out.println("sender2 : " + msg2);
this.rabbitTemplate.convertAndSend("exchange", "topic.messages", msg2);
}
}
消费者
@Component
@RabbitListener(queues = "topic.message")
public class topicMessageReceiver {
@RabbitHandler
public void process(String msg) {
System.out.println("topicMessageReceiver : " +msg);
}
}
9.支持session集群
引入spring-session模块
application.properties增加如下配置
spring.session.store-type=redis
# spring session刷新模式:默认on-save
#spring.session.redis.flush-mode=on-save
#spring.session.redis.namespace=
# session超时时间,单位秒
#server.session.timeout=30
10.支持线上基于HTTP的监控
引入spring-boot-starter-actuator、spring-boot-starter-security模块
application.properties增加如下配置
#端点的配置
endpoints.sensitive=true
endpoints.shutdown.enabled=true
#保护端点
security.basic.enabled=true
security.user.name=
security.user.password=
management.security.roles=SUPERUSER
#自定义路径
security.basic.path=/manage
management.context-path=/manage
度量:http://localhost:8080/manage/metrics
追踪:http://localhost:8080/manage/trace
11.支持线程池druid以及线上监控
引入druid、spring-boot-starter-aop模块
application.properties增加如下配置
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
#初始化连接大小
spring.datasource.druid.initial-size=8
#最小空闲连接数
spring.datasource.druid.min-idle=5
#最大连接数
spring.datasource.druid.max-active=10
#查询超时时间
spring.datasource.druid.query-timeout=6000
#事务查询超时时间
spring.datasource.druid.transaction-query-timeout=6000
#关闭空闲连接超时时间
spring.datasource.druid.remove-abandoned-timeout=1800
spring.datasource.druid.filter-class-names=stat
spring.datasource.druid.filters=stat,config
druid-bean.xml增加如下
com.roncoo.education.mapper.*
代码
@Configuration
public class DruidConfiguration {
@ConditionalOnClass(DruidDataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = true)
static class Druid extends DruidConfiguration {
@Bean
@ConfigurationProperties("spring.datasource.druid")
public DruidDataSource dataSource(DataSourceProperties properties) {
DruidDataSource druidDataSource = (DruidDataSource) properties.initializeDataSourceBuilder().type(DruidDataSource.class).build();
DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(properties.determineUrl());
String validationQuery = databaseDriver.getValidationQuery();
if (validationQuery != null) {
druidDataSource.setValidationQuery(validationQuery);
}
return druidDataSource;
}
}
}
@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*", initParams = { @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*") })
public class DruidWebStatFilter extends WebStatFilter {
}
@WebServlet(urlPatterns = { "/druid/*" }, initParams = { @WebInitParam(name = "loginUsername", value = ""), @WebInitParam(name = "loginPassword", value = "") })
public class DruidStatViewServlet extends StatViewServlet {
private static final long serialVersionUID = 1L;
}
ps:最后一个支持druid线上监控配置有点多,配置文件application.properties设置初始参数;druid-bean.xml设置aop对应监控页面的spring拦截方法功能;DruidConfiguration 是为了支持application.properties配置的多参数;DruidWebStatFilter 这个过滤器是为了支持监控页面的web监控功能;DruidStatViewServlet 是为了支持监控页面并且加上了登录校验