springboot基础深入学习,springboot集成框架整合
1.springboot入门
1.1优点
快速创建独立运行的spring项目以及与主流框架集成
使用嵌入式的servlet,应用无需打成war包
starters自动依赖与版本控制
大量的自动配置,简化开发,也可修改默认值
无需配置xml,无代码生成,开箱即用
准生产环境的应用时运行监控
与云计算天然集成
1.2创建可执行的jar
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
1.3获取配置文件之注入
[email protected]获取
引入pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
yml文件
person: name: 张无忌 age: 18 boss: false birth: 2001/08/01 map: "[大老婆]": 赵敏 k1: 周芷若 list: - 长腿妹子 - 大胸妹 - 女汉子 dog: name: 花花 age: 5
javabean
/** * 将配置文件中的值映射到实体中 * @ConfigurationProperties将实体类中的属性和配置文件中的配置进行绑定映射 * (prefix="person")配置文件中的哪个属性 */ @Component @ConfigurationProperties(prefix="person") public class Person { private String name; private Integer age; private boolean boss; private Date birth; private Map<String,String> map; private List<String> list; private Dog dog;
[email protected]获取值
@Component public class Person { @Value("${person.name}") private String name; @Value("#{11*22}")
[email protected]获取值和@ConfigurationProperties获取区别
@ConfigurationProperties | @value | |
---|---|---|
功能上 | 可以批量注入 | 一个一个注入 |
松散绑定 | 支持(lastName == last_Name) | 不支持 |
spEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
封装复杂数据类型 | 支持 | 不支持 |
数据校验
@Component @ConfigurationProperties(prefix="person") @Validated public class Person { private String name; @Max(15) private Integer age;
1.3.4 @PropertySource & @ImportResource
@PropertySource加载指定的配置文件
@Component @PropertySource(value = {"classpath:person.properties"}) public class Person { private String name; private Integer age; private boolean boss;
@ImportResource :导入spring的配置文件,使配置文件生效
@ImportResource(locations = {"classpath:bean.xml"}) @SpringBootApplication public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
springboot推荐使用全注解的方式:编写配置类
/** * 指明当前类是配置类替代spring的xml配置文件 */ @Configuration public class MyConfig { /** * 默认id就是方法名 * @return */ @Bean public HelloService helloService(){ return new HelloService(); } }
测试代码
@Test public void testConfig(){ boolean b = ioc.containsBean("helloService"); System.out.println(b); }
1.3.5配置随机数/占位符
my.secret=${random.value} my.number=${random.int} my.bignumber=${random.long} my.uuid=${random.uuid} my.number.less.than.ten=${random.int(10)} my.number.in.range=${random.int[1024,65536]}
app.name=MyApp app.description=${app.name} is a Spring Boot application
1.4 yml代码块配置多文件
server: address: 192.168.1.100 spring: profiles: active: development --- spring: profiles: development server: address: 127.0.0.1 --- spring: profiles: production & eu-central server: address: 192.168.1.120
1.5配置文件加载位置
SpringApplication从
application.properties以下位置的文件加载属性并将它们添加到Spring
Environment`:
-
一个
/config
当前目录的子目录 -
当前目录
-
一个classpath
/config
包 -
类路径根
默认情况下,配置的位置是 classpath:/,classpath:/config/,file:./,file:./config/
。生成的搜索顺序如下:
-
file:./config/
-
file:./
-
classpath:/config/
-
classpath:/
spring.config.location改变默认配置文件的位置
java -jar ****.jar --spring.config.location=G:/application.properties
1.6外部配置的加载顺序
springboot也可以从以下位置加载,优先级由高到低,高优先级会覆盖低优先级,所有配置形成互补配置
命令行参数 举例:java -jar .jar --server.port=8080
@TestPropertySource 你的测试注释。 properties属性测试。可 用于测试特定应用程序片段@SpringBootTest的 测试注释。 命令行参数。 来自SPRING_APPLICATION_JSON(嵌入在环境变量或系统属性中的内联JSON)的属性。 ServletConfig init参数。 ServletContext init参数。 JNDI属性来自java:comp/env。 Java系统属性(System.getProperties())。 OS环境变量。 一RandomValuePropertySource,只有在拥有性能random.*。 由jar包外向内寻找,优先加载带profile jar之外(application-{profile}.properties和YAML变体)。 打包在jar中的特定于配置文件的应用程序属性(application-{profile}.properties 以及YAML变体)。
再加载不带profile的 打包jar之外的应用程序属性(application.properties以及YAML变体)。 打包在jar中的应用程序属性(application.properties和YAML变体)。 @PropertySource 你的@Configuration课上的注释。 默认属性(由设置指定SpringApplication.setDefaultProperties)。
官方文档
2.自动配置原理
2.1配置文件能配置的属性参照官方文档
2.2自动配置原理
springboot在加载主启动类的时候,开启自动配置功能@EnableAutoConfiguration
@EnableAutoConfiguration作用:利用@Import({AutoConfigurationImportSelector.class})给容器导入组件
以HttpEncodingAutoConfiguration为例
@Configuration //表示这是一个配置类 @EnableConfigurationProperties({HttpProperties.class})//启用指定类的(HttpProperties)ConfigurationProperties功能,将配置文件中的对应的值HttpProperties绑定起来 @ConditionalOnWebApplication( type = Type.SERVLET )//spring底层注解 @Conditional根据不同的条件,如果满足条件,整个配置类的配置才会生效 @ConditionalOnClass({CharacterEncodingFilter.class})//判断当前项目有没有CharacterEncodingFilter类,解决springmvc中的乱码问题,之前配置在web.xml中 @ConditionalOnProperty( prefix = "spring.http.encoding", value = {"enabled"}, matchIfMissing = true )//判断配置文件中是否存在某个配置,spring.http.encoding.enabled,如果不存在判断也是成立的。即使在配置文件中不配置spring.http.encoding.enabled,也默认生效 (matchIfMissing = true)
@ConfigurationProperties( prefix = "spring.http" )//从配置文件中获取属性值与对应的bean的属性进行绑定 public class HttpProperties { private boolean logRequestDetails; private final HttpProperties.Encoding encoding = new HttpProperties.Encoding();
所有的能在配置文件中的属性都是在***Properties类中封装着,配置文件能配置的属性参考属性所对应的类的属性
2.3 @Conditional注解详解配置
@Conditional注解扩展 | 作用:是否满足当前指定条件 |
---|---|
@ConditionalOnJava | 系统的java版本是否符合要求 |
@ConditionalOnBean | 容器中存在指定的Bean |
@ConditionalOnMissingBean | 容器中不存在指定的Bean |
@ConditionalOnExpression | 满足spEL表达式指定 |
@ConditionalOnClass | 系统中有指定的类 |
@ConditionalOnMissingClass | 系统中没有指定的类 |
@ConditionalOnSingleCandidate | 容器中只有一个指定的bean,或者这个bean是首选的bean |
@ConditionalOnProperty | 系统中指定的属性是否有指定的值 |
@ConditionalOnResource | 类路径下是否有指定的资源 |
@ConditionalOnWebApplication | 当前是web环境 |
@ConditionalOnNotWebApplication | 当前不是web环境 |
@ConditionalOnJndi | Jndi存在指定项 |
2.4哪些配置类生效
要知道哪些配置类生效,在配置文件中配置 debug = true,控制台就可以打印自动配置报告
3.日志
3.1springboot默认使用logback,slf4j
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloWorld { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.info("Hello World"); } }
引入的框架有各自的日志框架,要统一日志框架
将原有的各自框架的日志包排除出去
用中间包替换替换原有的日志框架
slf4的其他实现
3.2springboot日志引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> <version>2.1.6.RELEASE</version> <scope>compile</scope> </dependency>
如果要引入其他的框架,框架中自带的自带的日志框架依赖要排除掉
3.3日志测试
Logger logger = LoggerFactory.getLogger(getClass()); public void testConfig(){ //日志级别由低到高 logger.trace("这是trace日志"); boolean b = ioc.containsBean("helloService"); logger.debug("debug调试"+b); logger.info("info调试"+b); logger.warn("日志警告。。。。。。。。。。。。"); logger.error("错误日志"); } //springboot默认使用info级别,所以会打印info,warn,error
配置文件修改日志级别
logging.level.it.com.cn=debug
logging.file | logging.path | 例 | 描述 |
---|---|---|---|
*没有 | 没有 | 仅控制台记录。 | |
具体文件 | 没有 | my.log | |
没有 | 具体目录 | /var/log | 写入spring.log 指定的目录。名称可以是精确位置或相对于当前目录。 |
指定日志配置
Logging System | Customization |
---|---|
Logback |
logback-spring.xml , logback-spring.groovy , logback.xml , or logback.groovy
|
Log4j2 |
log4j2-spring.xml or log4j2.xml
|
JDK (Java Util Logging) | logging.properties |
注意:
logback.xml直接可以被日志框架识别加载
logback-spring.xml无法被日志框架识别加载,由springboot识别加载,可以使用springboot的高级功能
<springProfile name = “staging” > <! - “暂存”配置文件处于活动状态时启用的配置 - > </ springProfile> <springProfile name = “dev | staging” > <! - 在“dev”或“staging”配置文件处于活动状态时启用的配置 - > </ springProfile> <springProfile name = “!production” > <! - “生产”配置文件未**时要启用的配置 - > </ springProfile>
4.web开发
4.1引入静态资源
默认情况下,Spring Boot从类路径中的/static
( /public
或/resources
或/META-INF/resources
)目录或者根目录中提供静态内容ServletContext
还可以使用该spring.resources.static-locations
属性自定义静态资源位置 (将默认值替换为目录位置列表)
4.2环境搭建
引入thymeleaf模板
<!--引入thymeleaf模板--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--切换版本--> <properties> <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version> </properties>
使用规则
@ConfigurationProperties( prefix = "spring.thymeleaf" ) public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; private boolean checkTemplate = true; private boolean checkTemplateLocation = true; private String prefix = "classpath:/templates/"; private String suffix = ".html"; private String mode = "HTML";
导入名称空间,为了有语法提示
<html xmlns:th="http://www.thymeleaf.org">
4.3Spring MVC自动配置
Spring Boot为Spring MVC提供自动配置,适用于大多数应用程序。
自动配置在Spring的默认值之上添加了以下功能:
-
包含
ContentNegotiatingViewResolver
和BeanNameViewResolver
类。 -
支持提供静态资源,包括对WebJars的支持(见下文)。
-
自动登记
Converter
,GenericConverter
,Formatter
类。 -
支持
HttpMessageConverters
(见下文)。 -
自动注册
MessageCodesResolver
(见下文)。 -
静态
index.html
支持。 -
自定义
Favicon
支持(见下文)。 -
自动使用
ConfigurableWebBindingInitializer
bean(见下文)。
如果你想保留Spring Boot MVC功能,并且你只想添加额外的MVC配置(拦截器,格式化程序,视图控制器等),你可以添加自己的@Configuration
类类型WebMvcConfigurerAdapter
,但没有 @EnableWebMvc
。如果您希望提供自定义实例RequestMappingHandlerMapping
,RequestMappingHandlerAdapter
或者ExceptionHandlerExceptionResolver
您可以声明WebMvcRegistrationsAdapter
提供此类组件的实例。
如果您想完全控制Spring MVC,可以添加自己的@Configuration
注释@EnableWebMvc
。
2.1.6版本
Spring Boot为Spring MVC提供自动配置,适用于大多数应用程序。
自动配置在Spring的默认值之上添加了以下功能:
-
包含
ContentNegotiatingViewResolver
和BeanNameViewResolver
类。 -
支持提供静态资源,包括对WebJars的支持( 本文档稍后介绍))。
-
自动注册
Converter
,GenericConverter
和Formatter
类。 -
支持
HttpMessageConverters
( 本文档后面部分)。 -
自动注册
MessageCodesResolver
( 本文档后面部分)。 -
静态
index.html
支持。 -
自定义
Favicon
支持(本文档稍后介绍)。 -
自动使用
ConfigurableWebBindingInitializer
bean( 本文档稍后介绍)。
如果您想保留Spring Boot MVC功能并且想要添加其他 MVC配置(拦截器,格式化程序,视图控制器和其他功能),您可以添加自己的@Configuration
类类型WebMvcConfigurer
但不需要 @EnableWebMvc
。如果您希望提供,或的 自定义实例RequestMappingHandlerMapping
,则可以声明 实例以提供此类组件。RequestMappingHandlerAdapter``ExceptionHandlerExceptionResolver``WebMvcRegistrationsAdapter
如果您想完全控制Spring MVC,可以添加自己的@Configuration
注释@EnableWebMvc
。
package it.com.cn.springboot.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 保留Spring Boot MVC功能并且想要添加其他 MVC配置 */ @Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { //浏览器发送/itGetAll请求,请求到success页面 registry.addViewController("/itGetAll").setViewName("success"); } }
5.springboot错误处理
自定义返回json格式的异常
==**@ControllerAdvice
以自定义要为特定控制器和/或异常类型返回的JSON文档==**
@ControllerAdvice(basePackageClasses = AcmeController.class) public class AcmeControllerAdvice extends ResponseEntityExceptionHandler { @ExceptionHandler(YourException.class) @ResponseBody ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) { HttpStatus status = getStatus(request); return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } }
package it.com.cn.springboot.exception; /** * 自定义异常 */ public class UserNotExistException extends RuntimeException{ public UserNotExistException() { super("用户不存在!!!!"); } } package it.com.cn.springboot.controller; import it.com.cn.springboot.exception.UserNotExistException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; /** * 自定义异常信息json格式 */ @ControllerAdvice public class MyExceptionHandler { @ResponseBody @ExceptionHandler(UserNotExistException.class) public Map<String,Object> handlerException(Exception e){ Map<String, Object> map = new HashMap<>(); map.put("code","user is not exist!!!"); map.put("msg",e.getMessage()); return map; } } //没有实现自适应效果
转发到error进行自适应处理
//自适应浏览器和客户端 @ExceptionHandler(UserNotExistException.class) public String handlerException(Exception e){ Map<String, Object> map = new HashMap<>(); map.put("code","user is not exist!!!"); map.put("msg",e.getMessage()); //转发到error return "forward/error"; }
将自己定义的异常信息携带出去
package it.com.cn.springboot.component; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; import java.util.Map; /** * 使异常返回结果中包含自己封装的信息 */ @Component public class MyErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace); map.put("msg","用户信息被禁言!!!!"); return map; } }
将自定义异常处理器中的错误信息也一并携带出去
@ExceptionHandler(UserNotExistException.class) public String handlerException(Exception e, HttpServletRequest request){ Map<String, Object> map = new HashMap<>(); map.put("code","user is not exist!!!"); map.put("message",e.getMessage()); //转发到error request.setAttribute("errormsg",map); return "forward/error"; } package it.com.cn.springboot.component; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; import java.util.Map; /** * 使异常返回结果中包含自己封装的信息 */ @Component public class MyErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace); map.put("msg","用户信息被禁言!!!!"); //将自定义的MyExceptionHandler的异常信息也获取封装到map中返回json Map<String, Object> errormsg = (Map<String, Object>) webRequest.getAttribute("errormsg", 0); map.put("errormsg",errormsg); return map; } }
6.配置嵌入式servlet容器
Spring Boot包括对嵌入式Tomcat, Jetty和 Undertow服务器的支持。大多数开发人员使用适当的“Starter”来获取完全配置的实例。默认情况下,嵌入式服务器侦听端口上的HTTP请求8080
。
6.1自定义嵌入式Servlet容器
可以使用Spring Environment
属性配置公共servlet容器设置。通常,可在application.properties
文件中定义属性。
常用服务器设置包括:
-
网络设置:侦听传入HTTP请求的端口(
server.port
),要绑定的接口地址server.address
等等。 -
会话设置:会话是持久性(
server.servlet.session.persistence
),会话超时(server.servlet.session.timeout
),会话数据(server.servlet.session.store-dir
)的位置以及会话cookie配置(server.servlet.session.cookie.*
)。 -
错误管理:错误页面的位置(
server.error.path
)等。
Spring Boot尽可能尝试公开常见设置,但这并不总是可行。对于这些情况,专用命名空间提供特定于服务器的自定义(请参阅 server.tomcat
和server.undertow
)。例如, 可以使用嵌入式servlet容器的特定功能配置访问日志。
请参阅 ServerProperties
课程以获取完整列表。
6.2程序化定制
如果需要以编程方式配置嵌入式servlet容器,可以注册实现该WebServerFactoryCustomizer
接口的Spring bean 。 WebServerFactoryCustomizer
提供对其的访问ConfigurableServletWebServerFactory
,其中包括许多自定义setter方法。以下示例以编程方式设置端口:
import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.stereotype.Component; @Component public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> { @Override public void customize(ConfigurableServletWebServerFactory server) { server.setPort(9000); } }
TomcatServletWebServerFactory
,JettyServletWebServerFactory
并且UndertowServletWebServerFactory
是专用变体,ConfigurableServletWebServerFactory
分别为Tomcat,Jetty和Undertow提供了额外的自定义setter方法。
6.2.1直接自定义ConfigurableServletWebServerFactory
如果前面的定制技术太有限,你可以注册 TomcatServletWebServerFactory
,JettyServletWebServerFactory
或 UndertowServletWebServerFactory
。
@Bean public ConfigurableServletWebServerFactory webServerFactory() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); factory.setPort(9000); factory.setSessionTimeout(10, TimeUnit.MINUTES); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html")); return factory; }
6.3注册Servlet
,Filter
或者Listener`
使用 ServletRegistrationBean
,FilterRegistrationBean
以及 ServletListenerRegistrationBean
类的完全控制
注册servlet
package it.com.cn.springboot.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 自定义servlet */ public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); resp.getWriter().print("===========自定义servlet"); resp.getWriter().write("自定义servlet"); } }
package it.com.cn.springboot.config; import it.com.cn.springboot.servlet.MyServlet; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyServerConfig { @Bean public ServletRegistrationBean doMyServlet(){ ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet"); return servletRegistrationBean; } }
注册filter
package it.com.cn.springboot.filter; import javax.servlet.*; import java.io.IOException; public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("自定义filter 执行。。。。。"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
注册listener
package it.com.cn.springboot.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("servlet======contextInitialized........."); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("servlet =========contextDestroyed"); } }
配置类
/** * 注册filter */ @Bean public FilterRegistrationBean doMyFilter(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new MyFilter()); filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet")); return filterRegistrationBean; } /** * 注冊listener * @return */ @Bean public ServletListenerRegistrationBean doMyListener(){ ServletListenerRegistrationBean<MyListener> listenerServletListenerRegistrationBean = new ServletListenerRegistrationBean<>(new MyListener()); return listenerServletListenerRegistrationBean; }
7.docker
uname -r //查看内核版本 移除旧的版本: yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ docker-latest-logrotate \ docker-logrotate \ docker-selinux \ docker-engine-selinux \ docker-engine 安装一些必要的系统工具: yum install -y yum-utils device-mapper-persistent-data lvm2 添加软件源信息 yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 安装 Docker-ce: yum -y install docker-ce 启动 Docker 后台服务 systemctl start docker 查看版本 docker -v systemctl enable docker //开机启动 常用命令 docker search mysql docker pull mysql:5.6 docker images |grep mysql 根据镜像启动容器 docker run --name my_mysql -d mysql:5.6 查看运行中的容器 docker ps 停止容器 docker start 容器id docker stop 容器id docker ps -a //查看所有运行的容器 docker -rm 容器id 删除容器 端口映射 docker run --name my_mysql -d -p 3306:3306 mysql:5.6 docker logs 容器id //查看日志
8.数据库访问
schema.sql,schema-all.sql 默认放在类路径下,创建表的语句就会执行建表语句 指定的话:spring.datasource.schema=classpath:dept.sql,user,sql
9.springboot启动配置原理
9.1启动流程
1.创建SpringbootApplication对象
initialize(source) 方法中会判断当前应用是不是web应用 会找到类路径下找到META-INF/spring.factories配置的所有的AppilcationContextInitializer,并保存在collection 再找到AppilcationContextListener 再找到朱配置类
2.运行run方法
获取SpringbootApplicationRunListener 类路径下找到META-INF/spring.factories
回调所有的SpringbootApplicationRunListener.starting()
10.整合redis
docker pull redis docker images //查看镜像 docker run --name my_redis -d -p 6379:6379 redis //启动 docker ps //Cannot restart container my_redis: driver failed programming external connectivity on endpoint my_redis (59a8ed1fddb4215f4039c0c041d328152d6e1bab49d5b17427f66f6cbb89543d): (iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0 --dport 6379 -j DNAT --to-destination 172.17.0.2:6379 ! -i docker0: iptables: No chain/target/match by that name. //解决方法 重启docker docker restart my_redis //重启容器 systemctl restart docker //重启docker
<!--redis spring-boot-starter-data-redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
11.整合rabbitmq
高级消息队列协议(AMQP)是面向消息的中间件的平台中立的线级协议。Spring AMQP项目将核心Spring概念应用于基于AMQP的消息传递解决方案的开发
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
docker pull registry.docker-cn.com/rabbitmq:3.7.17-management//中国镜像 docker pull rabbitmq:3.7.17-management docker run --name my_rabbitmq -d -p 5672:5672 -p 15672:15672 rabbitmq docker restart my_rabbitmq docker logs my_rabbitmq docker exec -it 64f2ef80a631 bash
**浏览器访问http://192.168.174.139:15672/无法进入的问题**
官网中有关于RabbitMQ管理控制台的说明,地址:https://www.rabbitmq.com/management.html(别问我怎么知道,我也是网上查的)。点击进去,其中前面部分就这么一段话描述:RabbitMQ包含有管理台插件,如果要使用,必须启动它
rabbitmq-plugins enable rabbitmq_management**
rabbitMq管理
docker exec -it 9cc78ba7ac32 bash进入到容器,然后执行如下命令 rabbitmqctl start_app rabbitmq-plugins enable rabbitmq_management rabbitmqctl stop docker restart my_rabbitmq 默认到guest/guest登录
exchanges
queues
队列和交换机绑定
topic
12.整合搜索 Elasticsearch
docker安装es
docker search elasticsearch docker pull elasticsearch docker pull elasticsearch:5.6.16 docker pull registry.docker-cn.com/library/elasticsearch:7.2.1 docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name myes 1e8add8d7b66 docker run -d -p 9200:9200 -p 9300:9300 --name myes 1e8add8d7b66
#