首页 文章 精选 留言 我的

精选列表

搜索[然之],共10000篇文章
优秀的个人博客,低调大师

11.OkHttp之java网络编程

1.TCP/IP协议家族 HTTP,FTP,DNS,TCP,UDP,IP OSI七层模型:应用层,表示层,会话层,传输层,网络层,数据链路层,物理层 五层协议: TCP三次握手(建立连接)和四次挥手(断开连接) HTTP请求:以报文形式通信 客户端请求Request:请求报文=请求头+空行+请求数据 Accept:客户端可以处理的数据格式 Cookie:服务端发送给客户端的cookie 服务端响应Response:响应报文=响应头+空行+响应数据 Content-Type:响应返回的类型(text/html;charset=utf-8) Set-Cookie:服务端给我们的cookie,要保存起来下次带过去 2.接口测试 搭建服务器: 1.下载Eclipse+Tomcat Eclipse Version: Luna Service Release 2 (4.4.2) Tomcat 7.0 2.配置Tomcat 配置tomcat.png 可能会存在的错误 Could not load the Tomcat server configuration at \Servers\Tomcat v5.5 Server at localhost-config. The configuration may be corrupt or incomplete. tomcat配置.png 其实主要是路径问题。解决方法就是将原来的server删掉,在添加一个server,设置server runtime ,tomcat安装目录设对 3.新建一个web工程 右键->new project选择web工程 新建web工程.png 4.将工程发布到tomcat,Add之后,start或者restart tomcat 部署项目到服务器.png 5.用浏览器测试项目工程 在web工程的WebContent目录下创建index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> Hello OkHttp! </body> </html> 在浏览器中输入http://192.168.1.107:8080/OkHttpServer,如果浏览器打印出Hello OkHttp!则证明成功 6.创建测试接口 import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 为什么eclipse不识别HttpServlet,因为没有servlet架包,要在项目中导入这个架包。 * 工程上右键,选择properties,然后选择java build path,library选项卡,add external jars, * 在tomcat的lib目录下找到servlet-api.jar,加载进来就可以了 * @author renzhenming */ @WebServlet("/TestServlet")//TestServlet前边这里如果不加"/"服务器启动不了(start failed) public class TestServlet 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 { //super.doPost(req, resp); PrintWriter writer = resp.getWriter(); writer.write("server data is coming"); writer.flush(); writer.close(); } } 这时候重新执行上一步骤,如果打印出server data is coming则证明测试接口成功,我们来详细看一下当这个请求发出时,两端的交互情况。在浏览器输入http://localhost:8080/OkHttpServer/TestServlet,右键 -->查看元素-->选择网络,此时我们回车浏览器会发送一次请求到服务端,也就是我们的本地服务器,看看此时网络中显示的,这些字段就不一一解释了,可以自己百度 网络请求头响应头.png 我们切换到cookie,可以看到此请求无cookie,那么cookie是什么,如果一个请求有cookie会怎样显示,这是接下来要说的内容 3.Cookie cookie是存放在客户端的信息,来自服务器,当客户端发送请求到服务器时,会携带cookie过去,如果用户离开网站,cookie会在一定时间内过期(相对危险) Session是存放在服务器上面的客户端的临时信息,用户离开网站会被清除(相对安全,但是会耗费资源) Token(令牌):用户身份验证,有点类似Cookie,相对来说更安全,一般流程: 1)客户端向服务端申请token 2)服务端收到请求,验证用户信息,签发一个token给客户端,自己保存token 3)客户端收到token会保存起来,每次请求带上token 4)服务器收到其他请求,会去验证客户端token,成功返回数据 创建一个用户登录servlet,模拟登录过程,当等成功之后,设置cookie返回给客户端,给cookie设置过期时间 import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; import bean.ResponseEntity; import bean.UserInfoEntity; @WebServlet("/LoginServlet") public class LoginServlet extends BaseJsonServlet{ private static final long serialVersionUID = 1L; @Override protected ResponseEntity onHandle(HttpServletRequest req, HttpServletResponse resp) throws Exception { ResponseEntity entity = new ResponseEntity(); entity.code = "0022"; entity.msg = "用户名或密码错误"; String userName = req.getParameter("userName"); if ("rzm".equals(userName)) { entity.code = "0000"; entity.msg = "登录成功"; UserInfoEntity usEntity = new UserInfoEntity(); usEntity.userName = userName; usEntity.userSex = "男"; entity.data = JSON.toJSONString(usEntity); Cookie cookie = new Cookie("userName", "rzm"); //设置cookie过期时间为一小时 cookie.setMaxAge(60*60); resp.addCookie(cookie); } return entity; } } 重新部署服务器,在浏览器中请求登录 http://localhost:8080/OkHttpServer/LoginServlet?userName=rzm 注意,这样设置的话,登录成功的提示会是乱码,我们需要设置content-type给响应头,这样就可以正常显示中文了 resp.setContentType("text/html;charset=utf-8"); 我们打开网页元素,看看此时的请求头和响应头有什么变化,第一次登录后服务器会返回一个cookie到客户端,此时由于本地没有cookie,所以请求头中不含有cookie,当第一次请求之后再次请求会携带cookie到服务器,前提是这个cookie没有过期,如果过期则不携带 cookie.png 模拟cookie过期的情况 创建一个用户评论servlet,当cookie存在且未过期时,评论成功,如果不存在或过期,提示用户未登录 import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.ResponseEntity; @WebServlet("/UserCommentServlet") public class UserCommentServlet extends BaseJsonServlet{ private static final long serialVersionUID = 1L; @Override protected ResponseEntity onHandle(HttpServletRequest req, HttpServletResponse resp) throws Exception { //判断该用户有没有登录,没有或cookie过期都不让评论 ResponseEntity entity = new ResponseEntity(); entity.code = "0033"; entity.msg = "评论失败,用户未登录"; Cookie cookies[] = req.getCookies(); if (cookies != null) { for(Cookie cookie:cookies){ String userName = cookie.getName(); if (userName != null) { entity.code = "0000"; entity.msg = "评论成功"; } } } return entity; } } 当用户登录之后由于本地已经保存了cookie,所以当调用评论接口的时候会检查cookie是否过期(过期则为null),如果过期则需要重新登录,我们把登录servlet中cookie过期的时间设置为10秒,登录之后10秒内调用评论接口 http://localhost:8080/OkHttpServer/UserCommentServlet 会告诉我们评论成功,但是如果超过十秒,那么就会返回用户未登录的提示

优秀的个人博客,低调大师

Java NIO 之 Buffer(缓冲区)

一 Buffer(缓冲区)介绍 Java NIO Buffers用于和NIO Channel交互。 我们从Channel中读取数据到buffers里,从Buffer把数据写入到Channels. Buffer本质上就是一块内存区,可以用来写入数据,并在稍后读取出来。这块内存被NIO Buffer包裹起来,对外提供一系列的读写方便开发的接口。 在Java NIO中使用的核心缓冲区如下(覆盖了通过I/O发送的基本数据类型:byte, char、short, int, long, float, double ,long): ByteBuffer CharBuffer ShortBuffer IntBuffer FloatBuffer DoubleBuffer LongBuffer 利用Buffer读写数据,通常遵循四个步骤: 把数据写入buffer; 调用flip; 从Buffer中读取数据; 调用buffer.clear()或者buffer.compact()。 当写入数据到buffer中时,buffer会记录已经写入的数据大小。当需要读数据时,通过 flip() 方法把buffer从写模式调整为读模式;在读模式下,可以读取所有已经写入的数据。 当读取完数据后,需要清空buffer,以满足后续写入操作。清空buffer有两种方式:调用 clear() 或 compact() 方法。clear会清空整个buffer,compact则只清空已读取的数据,未被读取的数据会被移动到buffer的开始位置,写入位置则近跟着未读数据之后。 Buffer的容量,位置,上限(Buffer Capacity, Position and Limit) Buffer缓冲区实质上就是一块内存,用于写入数据,也供后续再次读取数据。这块内存被NIO Buffer管理,并提供一系列的方法用于更简单的操作这块内存。 一个Buffer有三个属性是必须掌握的,分别是: capacity容量 position位置 limit限制 position和limit的具体含义取决于当前buffer的模式。capacity在两种模式下都表示容量。 下面有张示例图,描诉了读写模式下position和limit的含义: 容量(Capacity) 作为一块内存,buffer有一个固定的大小,叫做capacit(容量)。也就是最多只能写入容量值得字节,整形等数据。一旦buffer写满了就需要清空已读数据以便下次继续写入新的数据。 位置(Position) 当写入数据到Buffer的时候需要从一个确定的位置开始,默认初始化时这个位置position为0,一旦写入了数据比如一个字节,整形数据,那么position的值就会指向数据之后的一个单元,position最大可以到capacity-1. 当从Buffer读取数据时,也需要从一个确定的位置开始。buffer从写入模式变为读取模式时,position会归零,每次读取后,position向后移动。 上限(Limit) 在写模式,limit的含义是我们所能写入的最大数据量,它等同于buffer的容量。 一旦切换到读模式,limit则代表我们所能读取的最大数据量,他的值等同于写模式下position的位置。换句话说,您可以读取与写入数量相同的字节数(限制设置为写入的字节数,由位置标记)。 二 Buffer的常见方法 方法 介绍 abstract Object array() 返回支持此缓冲区的数组 (可选操作) abstract int arrayOffset() 返回该缓冲区的缓冲区的第一个元素的背衬数组中的偏移量 (可选操作) int capacity() 返回此缓冲区的容量 Buffer clear() 清除此缓存区。将position = 0;limit = capacity;mark = -1; Buffer flip() flip()方法可以吧Buffer从写模式切换到读模式。调用flip方法会把position归零,并设置limit为之前的position的值。 也就是说,现在position代表的是读取位置,limit标示的是已写入的数据位置。 abstract boolean hasArray() 告诉这个缓冲区是否由可访问的数组支持 boolean hasRemaining() return position < limit,返回是否还有未读内容 abstract boolean isDirect() 判断个缓冲区是否为 direct abstract boolean isReadOnly() 判断告知这个缓冲区是否是只读的 int limit() 返回此缓冲区的限制 Buffer position(int newPosition) 设置这个缓冲区的位置 int remaining() return limit - position; 返回limit和position之间相对位置差 Buffer rewind() 把position设为0,mark设为-1,不改变limit的值 Buffer mark() 将此缓冲区的标记设置在其位置 三 Buffer的使用方式/方法介绍 分配缓冲区(Allocating a Buffer) 为了获得缓冲区对象,我们必须首先分配一个缓冲区。在每个Buffer类中,allocate()方法用于分配缓冲区。 下面来看看ByteBuffer分配容量为28字节的例子: ByteBuffer buf = ByteBuffer.allocate(28); 下面来看看另一个示例:CharBuffer分配空间大小为2048个字符。 CharBuffer buf = CharBuffer.allocate(2048); 写入数据到缓冲区(Writing Data to a Buffer) 写数据到Buffer有两种方法: 从Channel中写数据到Buffer 手动写数据到Buffer,调用put方法 下面是一个实例,演示从Channel写数据到Buffer: int bytesRead = inChannel.read(buf); //read into buffer. 通过put写数据: buf.put(127); put方法有很多不同版本,对应不同的写数据方法。例如把数据写到特定的位置,或者把一个字节数据写入buffer。看考JavaDoc文档可以查阅的更多数据。 翻转(flip()) flip()方法可以吧Buffer从写模式切换到读模式。调用flip方法会把position归零,并设置limit为之前的position的值。 也就是说,现在position代表的是读取位置,limit标示的是已写入的数据位置。 从Buffer读取数据(Reading Data from a Buffer) 从Buffer读数据也有两种方式。 从buffer读数据到channel 从buffer直接读取数据,调用get方法 读取数据到channel的例子: int bytesWritten = inChannel.write(buf); 调用get读取数据的例子: byte aByte = buf.get(); get也有诸多版本,对应了不同的读取方式。 rewind() Buffer.rewind()方法将position置为0,这样我们可以重复读取buffer中的数据。limit保持不变。 clear() and compact() 一旦我们从buffer中读取完数据,需要复用buffer为下次写数据做准备。只需要调用clear()或compact()方法。 如果调用的是clear()方法,position将被设回0,limit被设置成 capacity的值。换句话说,Buffer 被清空了。Buffer中的数据并未清除,只是这些标记告诉我们可以从哪里开始往Buffer里写数据。 如果Buffer还有一些数据没有读取完,调用clear就会导致这部分数据被“遗忘”,因为我们没有标记这部分数据未读。 针对这种情况,如果需要保留未读数据,那么可以使用compact。 因此 compact() 和 clear() 的区别就在于: 对未读数据的处理,是保留这部分数据还是一起清空 。 mark()与reset()方法 通过调用Buffer.mark()方法,可以标记Buffer中的一个特定position。之后可以通过调用Buffer.reset()方法恢复到这个position。例如: buffer.mark(); //call buffer.get() a couple of times, e.g. during parsing. buffer.reset(); //set position back to mark. equals() and compareTo() 可以用eqauls和compareTo比较两个buffer equals(): 判断两个buffer相对,需满足: 类型相同 buffer中剩余字节数相同 所有剩余字节相等 从上面的三个条件可以看出,equals只比较buffer中的部分内容,并不会去比较每一个元素。 compareTo(): compareTo也是比较buffer中的剩余元素,只不过这个方法适用于比较排序的: 四 Buffer常用方法测试 这里以ByteBuffer为例子说明抽象类Buffer的实现类的一些常见方法的使用: package channel; import java.nio.ByteBuffer; public class ByteBufferMethods { public static void main(String args[]){ //分配缓冲区(Allocating a Buffer) ByteBuffer buffer = ByteBuffer.allocate(33); System.out.println("-------------Test reset-------------"); //clear()方法,position将被设回0,limit被设置成 capacity的值 buffer.clear(); // 设置这个缓冲区的位置 buffer.position(5); //将此缓冲区的标记设置在其位置。没有buffer.mark();这句话会报错 buffer.mark(); buffer.position(10); System.out.println("before reset: " + buffer); //将此缓冲区的位置重置为先前标记的位置。(buffer.position(5)) buffer.reset(); System.out.println("after reset: " + buffer); System.out.println("-------------Test rewind-------------"); buffer.clear(); buffer.position(10); //返回此缓冲区的限制。 buffer.limit(15); System.out.println("before rewind: " + buffer); //把position设为0,mark设为-1,不改变limit的值 buffer.rewind(); System.out.println("before rewind: " + buffer); System.out.println("-------------Test compact-------------"); buffer.clear(); buffer.put("abcd".getBytes()); System.out.println("before compact: " + buffer); System.out.println(new String(buffer.array())); //limit = position;position = 0;mark = -1; 翻转,也就是让flip之后的position到limit这块区域变成之前的0到position这块, //翻转就是将一个处于存数据状态的缓冲区变为一个处于准备取数据的状态 buffer.flip(); System.out.println("after flip: " + buffer); //get()方法:相对读,从position位置读取一个byte,并将position+1,为下次读写作准备 System.out.println((char) buffer.get()); System.out.println((char) buffer.get()); System.out.println((char) buffer.get()); System.out.println("after three gets: " + buffer); System.out.println("\t" + new String(buffer.array())); //把从position到limit中的内容移到0到limit-position的区域内,position和limit的取值也分别变成limit-position、capacity。 // 如果先将positon设置到limit,再compact,那么相当于clear() buffer.compact(); System.out.println("after compact: " + buffer); System.out.println("\t" + new String(buffer.array())); System.out.println("-------------Test get-------------"); buffer = ByteBuffer.allocate(32); buffer.put((byte) 'a').put((byte) 'b').put((byte) 'c').put((byte) 'd') .put((byte) 'e').put((byte) 'f'); System.out.println("before flip(): " + buffer); // 转换为读取模式 buffer.flip(); System.out.println("before get(): " + buffer); System.out.println((char) buffer.get()); System.out.println("after get(): " + buffer); // get(index)不影响position的值 System.out.println((char) buffer.get(2)); System.out.println("after get(index): " + buffer); byte[] dst = new byte[10]; buffer.get(dst, 0, 2); System.out.println("after get(dst, 0, 2): " + buffer); System.out.println("\t dst:" + new String(dst)); System.out.println("buffer now is: " + buffer); System.out.println("\t" + new String(buffer.array())); System.out.println("-------------Test put-------------"); ByteBuffer bb = ByteBuffer.allocate(32); System.out.println("before put(byte): " + bb); System.out.println("after put(byte): " + bb.put((byte) 'z')); System.out.println("\t" + bb.put(2, (byte) 'c')); // put(2,(byte) 'c')不改变position的位置 System.out.println("after put(2,(byte) 'c'): " + bb); System.out.println("\t" + new String(bb.array())); // 这里的buffer是 abcdef[pos=3 lim=6 cap=32] bb.put(buffer); System.out.println("after put(buffer): " + bb); System.out.println("\t" + new String(bb.array())); } } 参考: 官方JDK相关文档 谷歌搜索排名第一的Java NIO教程 《Java程序员修炼之道》 ByteBuffer常用方法详解 Java NIO 易百教程 欢迎关注我的微信公众号:"Java面试通关手册"(一个有温度的微信公众号,期待与你共同进步~~~坚持原创,分享美文,分享各种Java学习资源):

优秀的个人博客,低调大师

深入理解SpringBoot之自动装配

SpringBoot的自动装配是拆箱即用的基础,也是微服务化的前提。其实它并不那么神秘,我在这之前已经写过最基本的实现了,大家可以参考这篇文章。这次主要的议题是,来看看它是怎么样实现的,我们透过源代码来把握自动装配的来龙去脉。 一、自动装配过程分析 1.1、关于@SpringBootApplication 我们在编写SpringBoot项目时,@SpringBootApplication是最常见的注解了,我们可以看一下源代码: /* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.context.TypeExcludeFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.core.annotation.AliasFor; /** * Indicates a {@link Configuration configuration} class that declares one or more * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration * auto-configuration} and {@link ComponentScan component scanning}. This is a convenience * annotation that is equivalent to declaring {@code @Configuration}, * {@code @EnableAutoConfiguration} and {@code @ComponentScan}. * * @author Phillip Webb * @author Stephane Nicoll * @since 1.2.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { /** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */ @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude") Class<?>[] exclude() default {}; /** * Exclude specific auto-configuration class names such that they will never be * applied. * @return the class names to exclude * @since 1.3.0 */ @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName") String[] excludeName() default {}; /** * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses} * for a type-safe alternative to String-based package names. * @return base packages to scan * @since 1.3.0 */ @AliasFor(annotation = ComponentScan.class, attribute = "basePackages") String[] scanBasePackages() default {}; /** * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to * scan for annotated components. The package of each class specified will be scanned. * <p> * Consider creating a special no-op marker class or interface in each package that * serves no purpose other than being referenced by this attribute. * @return base packages to scan * @since 1.3.0 */ @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses") Class<?>[] scanBasePackageClasses() default {}; } View Code 这里面包含了@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan,此处@ComponentScan由于没有指定扫描包,因此它默认扫描的是与该类同级的类或者同级包下的所有类,另外@SpringBootConfiguration,通过源码得知它是一个@Configuration: /* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Configuration; /** * Indicates that a class provides Spring Boot application * {@link Configuration @Configuration}. Can be used as an alternative to the Spring's * standard {@code @Configuration} annotation so that configuration can be found * automatically (for example in tests). * <p> * Application should only ever include <em>one</em> {@code @SpringBootConfiguration} and * most idiomatic Spring Boot applications will inherit it from * {@code @SpringBootApplication}. * * @author Phillip Webb * @since 1.4.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration public @interface SpringBootConfiguration { } View Code 由此我们可以推断出@SpringBootApplication等同于@Configuration @ComponentScan @EnableAutoConfiguration 1.2、@EnableAutoConfiguration 一旦加上此注解,那么将会开启自动装配功能,简单点讲,Spring会试图在你的classpath下找到所有配置的Bean然后进行装配。当然装配Bean时,会根据若干个(Conditional)定制规则来进行初始化。我们看一下它的源码: /* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.support.SpringFactoriesLoader; /** * Enable auto-configuration of the Spring Application Context, attempting to guess and * configure beans that you are likely to need. Auto-configuration classes are usually * applied based on your classpath and what beans you have defined. For example, If you * have {@code tomcat-embedded.jar} on your classpath you are likely to want a * {@link TomcatEmbeddedServletContainerFactory} (unless you have defined your own * {@link EmbeddedServletContainerFactory} bean). * <p> * When using {@link SpringBootApplication}, the auto-configuration of the context is * automatically enabled and adding this annotation has therefore no additional effect. * <p> * Auto-configuration tries to be as intelligent as possible and will back-away as you * define more of your own configuration. You can always manually {@link #exclude()} any * configuration that you never want to apply (use {@link #excludeName()} if you don't * have access to them). You can also exclude them via the * {@code spring.autoconfigure.exclude} property. Auto-configuration is always applied * after user-defined beans have been registered. * <p> * The package of the class that is annotated with {@code @EnableAutoConfiguration}, * usually via {@code @SpringBootApplication}, has specific significance and is often used * as a 'default'. For example, it will be used when scanning for {@code @Entity} classes. * It is generally recommended that you place {@code @EnableAutoConfiguration} (if you're * not using {@code @SpringBootApplication}) in a root package so that all sub-packages * and classes can be searched. * <p> * Auto-configuration classes are regular Spring {@link Configuration} beans. They are * located using the {@link SpringFactoriesLoader} mechanism (keyed against this class). * Generally auto-configuration beans are {@link Conditional @Conditional} beans (most * often using {@link ConditionalOnClass @ConditionalOnClass} and * {@link ConditionalOnMissingBean @ConditionalOnMissingBean} annotations). * * @author Phillip Webb * @author Stephane Nicoll * @see ConditionalOnBean * @see ConditionalOnMissingBean * @see ConditionalOnClass * @see AutoConfigureAfter * @see SpringBootApplication */ @SuppressWarnings("deprecation") @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(EnableAutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; /** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */ Class<?>[] exclude() default {}; /** * Exclude specific auto-configuration class names such that they will never be * applied. * @return the class names to exclude * @since 1.3.0 */ String[] excludeName() default {}; } View Code 虽然根据文档注释的说明它指点我们去看EnableAutoConfigurationImportSelector。但是该类在SpringBoot1.5.X版本已经过时了,因此我们看一下它的父类AutoConfigurationImportSelector: /* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.Aware; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.DeferredImportSelector; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * {@link DeferredImportSelector} to handle {@link EnableAutoConfiguration * auto-configuration}. This class can also be subclassed if a custom variant of * {@link EnableAutoConfiguration @EnableAutoConfiguration}. is needed. * * @author Phillip Webb * @author Andy Wilkinson * @author Stephane Nicoll * @author Madhura Bhave * @since 1.3.0 * @see EnableAutoConfiguration */ public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered { private static final String[] NO_IMPORTS = {}; private static final Log logger = LogFactory .getLog(AutoConfigurationImportSelector.class); private ConfigurableListableBeanFactory beanFactory; private Environment environment; private ClassLoader beanClassLoader; private ResourceLoader resourceLoader; @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return NO_IMPORTS; } try { AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader); AnnotationAttributes attributes = getAttributes(annotationMetadata); List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); configurations = sort(configurations, autoConfigurationMetadata); Set<String> exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = filter(configurations, autoConfigurationMetadata); fireAutoConfigurationImportEvents(configurations, exclusions); return configurations.toArray(new String[configurations.size()]); } catch (IOException ex) { throw new IllegalStateException(ex); } } protected boolean isEnabled(AnnotationMetadata metadata) { return true; } /** * Return the appropriate {@link AnnotationAttributes} from the * {@link AnnotationMetadata}. By default this method will return attributes for * {@link #getAnnotationClass()}. * @param metadata the annotation metadata * @return annotation attributes */ protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) { String name = getAnnotationClass().getName(); AnnotationAttributes attributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(name, true)); Assert.notNull(attributes, "No auto-configuration attributes found. Is " + metadata.getClassName() + " annotated with " + ClassUtils.getShortName(name) + "?"); return attributes; } /** * Return the source annotation class used by the selector. * @return the annotation class */ protected Class<?> getAnnotationClass() { return EnableAutoConfiguration.class; } /** * Return the auto-configuration class names that should be considered. By default * this method will load candidates using {@link SpringFactoriesLoader} with * {@link #getSpringFactoriesLoaderFactoryClass()}. * @param metadata the source metadata * @param attributes the {@link #getAttributes(AnnotationMetadata) annotation * attributes} * @return a list of candidate configurations */ protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; } /** * Return the class used by {@link SpringFactoriesLoader} to load configuration * candidates. * @return the factory class */ protected Class<?> getSpringFactoriesLoaderFactoryClass() { return EnableAutoConfiguration.class; } private void checkExcludedClasses(List<String> configurations, Set<String> exclusions) { List<String> invalidExcludes = new ArrayList<String>(exclusions.size()); for (String exclusion : exclusions) { if (ClassUtils.isPresent(exclusion, getClass().getClassLoader()) && !configurations.contains(exclusion)) { invalidExcludes.add(exclusion); } } if (!invalidExcludes.isEmpty()) { handleInvalidExcludes(invalidExcludes); } } /** * Handle any invalid excludes that have been specified. * @param invalidExcludes the list of invalid excludes (will always have at least one * element) */ protected void handleInvalidExcludes(List<String> invalidExcludes) { StringBuilder message = new StringBuilder(); for (String exclude : invalidExcludes) { message.append("\t- ").append(exclude).append(String.format("%n")); } throw new IllegalStateException(String .format("The following classes could not be excluded because they are" + " not auto-configuration classes:%n%s", message)); } /** * Return any exclusions that limit the candidate configurations. * @param metadata the source metadata * @param attributes the {@link #getAttributes(AnnotationMetadata) annotation * attributes} * @return exclusions or an empty set */ protected Set<String> getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) { Set<String> excluded = new LinkedHashSet<String>(); excluded.addAll(asList(attributes, "exclude")); excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName"))); excluded.addAll(getExcludeAutoConfigurationsProperty()); return excluded; } private List<String> getExcludeAutoConfigurationsProperty() { if (getEnvironment() instanceof ConfigurableEnvironment) { RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( this.environment, "spring.autoconfigure."); Map<String, Object> properties = resolver.getSubProperties("exclude"); if (properties.isEmpty()) { return Collections.emptyList(); } List<String> excludes = new ArrayList<String>(); for (Map.Entry<String, Object> entry : properties.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (name.isEmpty() || name.startsWith("[") && value != null) { excludes.addAll(new HashSet<String>(Arrays.asList(StringUtils .tokenizeToStringArray(String.valueOf(value), ",")))); } } return excludes; } RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(getEnvironment(), "spring.autoconfigure."); String[] exclude = resolver.getProperty("exclude", String[].class); return (Arrays.asList(exclude == null ? new String[0] : exclude)); } private List<String> sort(List<String> configurations, AutoConfigurationMetadata autoConfigurationMetadata) throws IOException { configurations = new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata).getInPriorityOrder(configurations); return configurations; } private List<String> filter(List<String> configurations, AutoConfigurationMetadata autoConfigurationMetadata) { long startTime = System.nanoTime(); String[] candidates = configurations.toArray(new String[configurations.size()]); boolean[] skip = new boolean[candidates.length]; boolean skipped = false; for (AutoConfigurationImportFilter filter : getAutoConfigurationImportFilters()) { invokeAwareMethods(filter); boolean[] match = filter.match(candidates, autoConfigurationMetadata); for (int i = 0; i < match.length; i++) { if (!match[i]) { skip[i] = true; skipped = true; } } } if (!skipped) { return configurations; } List<String> result = new ArrayList<String>(candidates.length); for (int i = 0; i < candidates.length; i++) { if (!skip[i]) { result.add(candidates[i]); } } if (logger.isTraceEnabled()) { int numberFiltered = configurations.size() - result.size(); logger.trace("Filtered " + numberFiltered + " auto configuration class in " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) + " ms"); } return new ArrayList<String>(result); } protected List<AutoConfigurationImportFilter> getAutoConfigurationImportFilters() { return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, this.beanClassLoader); } private MetadataReaderFactory getMetadataReaderFactory() { try { return getBeanFactory().getBean( SharedMetadataReaderFactoryContextInitializer.BEAN_NAME, MetadataReaderFactory.class); } catch (NoSuchBeanDefinitionException ex) { return new CachingMetadataReaderFactory(this.resourceLoader); } } protected final <T> List<T> removeDuplicates(List<T> list) { return new ArrayList<T>(new LinkedHashSet<T>(list)); } protected final List<String> asList(AnnotationAttributes attributes, String name) { String[] value = attributes.getStringArray(name); return Arrays.asList(value == null ? new String[0] : value); } private void fireAutoConfigurationImportEvents(List<String> configurations, Set<String> exclusions) { List<AutoConfigurationImportListener> listeners = getAutoConfigurationImportListeners(); if (!listeners.isEmpty()) { AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, configurations, exclusions); for (AutoConfigurationImportListener listener : listeners) { invokeAwareMethods(listener); listener.onAutoConfigurationImportEvent(event); } } } protected List<AutoConfigurationImportListener> getAutoConfigurationImportListeners() { return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class, this.beanClassLoader); } private void invokeAwareMethods(Object instance) { if (instance instanceof Aware) { if (instance instanceof BeanClassLoaderAware) { ((BeanClassLoaderAware) instance) .setBeanClassLoader(this.beanClassLoader); } if (instance instanceof BeanFactoryAware) { ((BeanFactoryAware) instance).setBeanFactory(this.beanFactory); } if (instance instanceof EnvironmentAware) { ((EnvironmentAware) instance).setEnvironment(this.environment); } if (instance instanceof ResourceLoaderAware) { ((ResourceLoaderAware) instance).setResourceLoader(this.resourceLoader); } } } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory); this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } protected final ConfigurableListableBeanFactory getBeanFactory() { return this.beanFactory; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } protected ClassLoader getBeanClassLoader() { return this.beanClassLoader; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } protected final Environment getEnvironment() { return this.environment; } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } protected final ResourceLoader getResourceLoader() { return this.resourceLoader; } @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 1; } } View Code 首先该类实现了DeferredImportSelector接口,这个接口继承了ImportSelector: /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import org.springframework.core.type.AnnotationMetadata; /** * Interface to be implemented by types that determine which @{@link Configuration} * class(es) should be imported based on a given selection criteria, usually one or more * annotation attributes. * * <p>An {@link ImportSelector} may implement any of the following * {@link org.springframework.beans.factory.Aware Aware} interfaces, and their respective * methods will be called prior to {@link #selectImports}: * <ul> * <li>{@link org.springframework.context.EnvironmentAware EnvironmentAware}</li> * <li>{@link org.springframework.beans.factory.BeanFactoryAware BeanFactoryAware}</li> * <li>{@link org.springframework.beans.factory.BeanClassLoaderAware BeanClassLoaderAware}</li> * <li>{@link org.springframework.context.ResourceLoaderAware ResourceLoaderAware}</li> * </ul> * * <p>ImportSelectors are usually processed in the same way as regular {@code @Import} * annotations, however, it is also possible to defer selection of imports until all * {@code @Configuration} classes have been processed (see {@link DeferredImportSelector} * for details). * * @author Chris Beams * @since 3.1 * @see DeferredImportSelector * @see Import * @see ImportBeanDefinitionRegistrar * @see Configuration */ public interface ImportSelector { /** * Select and return the names of which class(es) should be imported based on * the {@link AnnotationMetadata} of the importing @{@link Configuration} class. */ String[] selectImports(AnnotationMetadata importingClassMetadata); } View Code 该接口主要是为了导入@Configuration的配置项,而DeferredImportSelector是延期导入,当所有的@Configuration都处理过后才会执行。 回过头来我们看一下AutoConfigurationImportSelector的selectImport方法: @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return NO_IMPORTS; } try { AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader); AnnotationAttributes attributes = getAttributes(annotationMetadata); List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); configurations = sort(configurations, autoConfigurationMetadata); Set<String> exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = filter(configurations, autoConfigurationMetadata); fireAutoConfigurationImportEvents(configurations, exclusions); return configurations.toArray(new String[configurations.size()]); } catch (IOException ex) { throw new IllegalStateException(ex); } } 该方法刚开始会先判断是否进行自动装配,而后会从META-INF/spring-autoconfigure-metadata.properties读取元数据与元数据的相关属性,紧接着会调用getCandidateConfigurations方法: /** * Return the auto-configuration class names that should be considered. By default * this method will load candidates using {@link SpringFactoriesLoader} with * {@link #getSpringFactoriesLoaderFactoryClass()}. * @param metadata the source metadata * @param attributes the {@link #getAttributes(AnnotationMetadata) annotation * attributes} * @return a list of candidate configurations */ protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; } /** * Return the class used by {@link SpringFactoriesLoader} to load configuration * candidates. * @return the factory class */ protected Class<?> getSpringFactoriesLoaderFactoryClass() { return EnableAutoConfiguration.class; } 在这里又遇到我们的老熟人了--SpringFactoryiesLoader, 它会读取META-INF/spring.factories下的EnableAutoConfiguration的配置,紧接着在进行排除与过滤,进而得到需要装配的类。最后让所有配置在META-INF/spring.factories下的AutoConfigurationImportListener执行AutoConfigurationImportEvent事件,代码如下: private void fireAutoConfigurationImportEvents(List<String> configurations, Set<String> exclusions) { List<AutoConfigurationImportListener> listeners = getAutoConfigurationImportListeners(); if (!listeners.isEmpty()) { AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, configurations, exclusions); for (AutoConfigurationImportListener listener : listeners) { invokeAwareMethods(listener); listener.onAutoConfigurationImportEvent(event); } } } protected List<AutoConfigurationImportListener> getAutoConfigurationImportListeners() { return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class, this.beanClassLoader); } 二、何时进行自动装配 在前面的环节里只是最终要确定哪些类需要被装配,在SpringBoot时何时处理这些自动装配的类呢?下面我们简要的分析一下: 2.1、AbstractApplicationContext的refresh方法: 这个方法老生常谈了其中请大家关注一下这个方法: // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); 在这里是处理BeanFactoryPostProcessor的,那么我们在来看一下这个接口BeanDefinitionRegistryPostProcessor: /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.support; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; /** * Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for * the registration of further bean definitions <i>before</i> regular * BeanFactoryPostProcessor detection kicks in. In particular, * BeanDefinitionRegistryPostProcessor may register further bean definitions * which in turn define BeanFactoryPostProcessor instances. * * @author Juergen Hoeller * @since 3.0.1 * @see org.springframework.context.annotation.ConfigurationClassPostProcessor */ public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor { /** * Modify the application context's internal bean definition registry after its * standard initialization. All regular bean definitions will have been loaded, * but no beans will have been instantiated yet. This allows for adding further * bean definitions before the next post-processing phase kicks in. * @param registry the bean definition registry used by the application context * @throws org.springframework.beans.BeansException in case of errors */ void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException; } View Code 该接口继承了BeanFactoryPostProcessor。 2.2、ConfigurationClassPostProcessor 类 该类主要处理@Configuration注解的,它实现了BeanDefinitionRegistryPostProcessor, 那么也间接实现了BeanFactoryPostProcessor,关键代码如下: @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { int factoryId = System.identityHashCode(beanFactory); if (this.factoriesPostProcessed.contains(factoryId)) { throw new IllegalStateException( "postProcessBeanFactory already called on this post-processor against " + beanFactory); } this.factoriesPostProcessed.add(factoryId); if (!this.registriesPostProcessed.contains(factoryId)) { // BeanDefinitionRegistryPostProcessor hook apparently not supported... // Simply call processConfigurationClasses lazily at this point then. processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory); } enhanceConfigurationClasses(beanFactory); beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory)); } /** * Build and validate a configuration model based on the registry of * {@link Configuration} classes. */ public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) { //.....省略部分代码 // Parse each @Configuration class ConfigurationClassParser parser = new ConfigurationClassParser( this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, this.componentScanBeanNameGenerator, registry); Set<BeanDefinitionHolder> candidates = new LinkedHashSet<BeanDefinitionHolder>(configCandidates); Set<ConfigurationClass> alreadyParsed = new HashSet<ConfigurationClass>(configCandidates.size()); do { parser.parse(candidates); parser.validate(); Set<ConfigurationClass> configClasses = new LinkedHashSet<ConfigurationClass>(parser.getConfigurationClasses()); configClasses.removeAll(alreadyParsed); // Read the model and create bean definitions based on its content if (this.reader == null) { this.reader = new ConfigurationClassBeanDefinitionReader( registry, this.sourceExtractor, this.resourceLoader, this.environment, this.importBeanNameGenerator, parser.getImportRegistry()); } this.reader.loadBeanDefinitions(configClasses); alreadyParsed.addAll(configClasses); candidates.clear(); if (registry.getBeanDefinitionCount() > candidateNames.length) { String[] newCandidateNames = registry.getBeanDefinitionNames(); Set<String> oldCandidateNames = new HashSet<String>(Arrays.asList(candidateNames)); Set<String> alreadyParsedClasses = new HashSet<String>(); for (ConfigurationClass configurationClass : alreadyParsed) { alreadyParsedClasses.add(configurationClass.getMetadata().getClassName()); } for (String candidateName : newCandidateNames) { if (!oldCandidateNames.contains(candidateName)) { BeanDefinition bd = registry.getBeanDefinition(candidateName); if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) && !alreadyParsedClasses.contains(bd.getBeanClassName())) { candidates.add(new BeanDefinitionHolder(bd, candidateName)); } } } candidateNames = newCandidateNames; } } while (!candidates.isEmpty()); // ....省略部分代码 } 其实这里注释已经很清楚了,我们可以清楚的看到解析每一个@ConfigurationClass的关键类是:ConfigurationClassParser,那么我们继续看一看这个类的parse方法: public void parse(Set<BeanDefinitionHolder> configCandidates) { this.deferredImportSelectors = new LinkedList<DeferredImportSelectorHolder>(); for (BeanDefinitionHolder holder : configCandidates) { BeanDefinition bd = holder.getBeanDefinition(); try { if (bd instanceof AnnotatedBeanDefinition) { parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName()); } else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) { parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName()); } else { parse(bd.getBeanClassName(), holder.getBeanName()); } } catch (BeanDefinitionStoreException ex) { throw ex; } catch (Throwable ex) { throw new BeanDefinitionStoreException( "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex); } } processDeferredImportSelectors(); } 在这里大家留意一下最后一句processDeferredImportSelectors方法,在这里将会对DeferredImportSelector进行处理,这样我们就和AutoConfigurationSelectImporter结合到一起了: private void processDeferredImportSelectors() { List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors; this.deferredImportSelectors = null; Collections.sort(deferredImports, DEFERRED_IMPORT_COMPARATOR); for (DeferredImportSelectorHolder deferredImport : deferredImports) { ConfigurationClass configClass = deferredImport.getConfigurationClass(); try { String[] imports = deferredImport.getImportSelector().selectImports(configClass.getMetadata()); processImports(configClass, asSourceClass(configClass), asSourceClasses(imports), false); } catch (BeanDefinitionStoreException ex) { throw ex; } catch (Throwable ex) { throw new BeanDefinitionStoreException( "Failed to process import candidates for configuration class [" + configClass.getMetadata().getClassName() + "]", ex); } } } 请大家关注这句代码:String[] imports = deferredImport.getImportSelector().selectImports(configClass.getMetadata());在这里deferredImport的类型为DeferredImportSelectorHolder: private static class DeferredImportSelectorHolder { private final ConfigurationClass configurationClass; private final DeferredImportSelector importSelector; public DeferredImportSelectorHolder(ConfigurationClass configClass, DeferredImportSelector selector) { this.configurationClass = configClass; this.importSelector = selector; } public ConfigurationClass getConfigurationClass() { return this.configurationClass; } public DeferredImportSelector getImportSelector() { return this.importSelector; } } 在这个内部类里持有了一个DeferredImportSelector的引用,至此将会执行自动装配的所有操作 三、总结 1)自动装配还是利用了SpringFactoriesLoader来加载META-INF/spring.factoires文件里所有配置的EnableAutoConfgruation,它会经过exclude和filter等操作,最终确定要装配的类 2) 处理@Configuration的核心还是ConfigurationClassPostProcessor,这个类实现了BeanFactoryPostProcessor, 因此当AbstractApplicationContext执行refresh方法里的invokeBeanFactoryPostProcessors(beanFactory)方法时会执行自动装配

优秀的个人博客,低调大师

docker拾遗-之再入坑

最近重新学习docker,好久不用,什么都是忘得差不多了,每天地铁看看视频,记记笔记,重新学习docker。 docker简介 什么是容器? 一种虚拟化的方案 操作系统级别的虚拟化 只能运行在相同或相似内核的操作系统 依赖于linux内核特性:Namespace和Cgroups(Control Group) linux容器 VS 虚拟机 使用的容量更小 什么是docker? 将应用程序自动部署到容器 GO语言开源引擎 2013 dotCloud 基于Apache 2.0开源授权协议发行 docker的目标 提供简单轻量的建模方式 职责的逻辑分离 快速高效的开发生命周期 鼓励使用面向服务的架构 docker的使用场景 使用docker容器开发测试,部署服务 创建隔离的运行环境 搭建测试环境 构建多用户的平台即服务(PaaS)基础设施 提供软件即服务(SaaS)应用程序 高性能、超大规模的宿主机部署 Docker容器相关技术 docker依赖的linux内核特性 NameSpaces命名空间 Control group (Cgroups)控制组 Namespace命名空间 编程语言 ​ 封装 -> 代码隔离 操作系统 ​ 系统资源的隔离 ​ 进程、网络、文件系统... PID (Process ID) 进程隔离 NET (Network) 管理网络接口 IPC (InterProcess Communication) 管理跨进程通信的访问 MNT (Mount) 管理挂载点 UTS (Unix TimeSharing System) 隔离内核和版本标识 Control groups 控制组 用来分配资源 来源于google Linux Kernel 2.6.24 @ 2007 资源限制 优先级设定 资源计量 资源控制 Docker容器的能力 文件系统隔离: 每个容器的都有自己的root文件系统 进程隔离: 每个容器都运行在自己的进程环境中 网络隔离: 容器的虚拟网络接口和IP地址是分开的 资源隔离和分组:使用Cgroups将CPU和内存之类的资源独立分配给每个Docker容器 ​

优秀的个人博客,低调大师

spark ML算法之线性回归使用

版权声明:本文由董可伦首发于https://dongkelun.com,非商业转载请注明作者及原创出处。商业转载请联系作者本人。 https://blog.csdn.net/dkl12/article/details/80259410 我的原创地址:https://dongkelun.com/2018/04/09/sparkMlLinearRegressionUsing/ 前言 本文是讲如何使用spark ml进行线性回归,不涉及线性回归的原理。 1、数据格式 1.1 普通标签格式 1.1.1 格式为: 标签,特征值1 特征值2 特征值3... 1,1.9 2,3.1 3,4 3.5,4.45 4,5.02 9,9.97 -2,-0.98 1.1.2 spark 读取 1、Rdd 旧版(mllib)的线性回归要求传入的参数类型为RDD[LabeledPoint] import org.apache.spark.SparkConf import org.apache.spark.SparkContext import org.apache.spark.mllib.linalg.Vectors import org.apache.spark.mllib.regression.LabeledPoint val data_path = "files/ml/linear_regression_data1.txt" val data = sc.textFile(data_path) val training = data.map { line => val arr = line.split(',') LabeledPoint(arr(0).toDouble, Vectors.dense(arr(1).split(' ').map(_.toDouble))) }.cache() training.foreach(println) 结果: (1.0,[1.9]) (2.0,[3.1]) (3.0,[4.0]) (3.5,[4.45]) (4.0,[5.02]) (9.0,[9.97]) (-2.0,[-0.98]) 一共有两列,第一列可以通过.label获得(类型为Double),第二列可以通过.features获得(类型为Vector[Double]) 2、 DataFrame 新版(ml)的线性回归要求传入的参数类型为Dataset[_] import org.apache.spark.ml.linalg.Vectors import org.apache.spark.sql.Row import spark.implicits._ val data_path = "files/ml/linear_regression_data1.txt" val data = spark.read.text(data_path) val training = data.map { case Row(line: String) => var arr = line.split(',') (arr(0).toDouble, Vectors.dense(arr(1).split(' ').map(_.toDouble))) }.toDF("label", "features") training.show() 结果: +-----+--------+ |label|features| +-----+--------+ | 1.0| [1.9]| | 2.0| [3.1]| | 3.0| [4.0]| | 3.5| [4.45]| | 4.0| [5.02]| | 9.0| [9.97]| | -2.0| [-0.98]| +-----+--------+ 其中列名”label”, “features”固定,不能改为其他列名。 1.2 LIBSVM格式 1.2.1 格式为: label index1:value1 index2:value2 ... 其中每一行的index必须为升序 为了便于理解,造几条多维数据: 1 1:1.9 2:2 4:2 100:3 101:6 2 1:3.1 2:2 4:2 100:3 101:6 3 1:4 2:2 4:2 100:3 101:6 3.5 1:4.45 2:2 4:2 100:3 101:6 4 1:5.02 2:2 4:2 100:3 101:6 9 1:9.97 4:2 100:3 101:6 -2 1:-0.98 2:2 4:2 100:3 201:6 1.2.2 spark 读取 1、Rdd import org.apache.spark.SparkConf import org.apache.spark.SparkContext import org.apache.spark.mllib.util.MLUtils val data_path = "files/ml/linear_regression_data2.txt" val training = MLUtils.loadLibSVMFile(sc, data_path) training.foreach(println) 结果: (1.0,(201,[0,1,3,99,100],[1.9,2.0,2.0,3.0,6.0])) (2.0,(201,[0,1,3,99,100],[3.1,2.0,2.0,3.0,6.0])) (3.0,(201,[0,1,3,99,100],[4.0,2.0,2.0,3.0,6.0])) (3.5,(201,[0,1,3,99,100],[4.45,2.0,2.0,3.0,6.0])) (4.0,(201,[0,1,3,99,100],[5.02,2.0,2.0,3.0,6.0])) (9.0,(201,[0,3,99,100],[9.97,2.0,3.0,6.0])) (-2.0,(201,[0,1,3,99,200],[-0.98,2.0,2.0,3.0,6.0])) 返回类型为RDD[LabeledPoint],其中第一列为label,第二列vector的第一个值为max(index),第二个index-1组成的数组,第三个为value组成的数组。 2、DataFrame val data_path = "files/ml/linear_regression_data2.txt" val data = spark.read.text(data_path) val training = spark.read.format("libsvm").load(data_path) training.show(false) 结果: +-----+--------------------------------------------+ |label|features | +-----+--------------------------------------------+ |1.0 |(201,[0,1,3,99,100],[1.9,2.0,2.0,3.0,6.0]) | |2.0 |(201,[0,1,3,99,100],[3.1,2.0,2.0,3.0,6.0]) | |3.0 |(201,[0,1,3,99,100],[4.0,2.0,2.0,3.0,6.0]) | |3.5 |(201,[0,1,3,99,100],[4.45,2.0,2.0,3.0,6.0]) | |4.0 |(201,[0,1,3,99,100],[5.02,2.0,2.0,3.0,6.0]) | |9.0 |(201,[0,3,99,100],[9.97,2.0,3.0,6.0]) | |-2.0 |(201,[0,1,3,99,200],[-0.98,2.0,2.0,3.0,6.0])| +-----+--------------------------------------------+ 2、线性回归代码 2.1 数据 用libsvm格式的数据: 1 1:1.9 2 1:3.1 3 1:4 3.5 1:4.45 4 1:5.02 9 1:9.97 -2 1:-0.98 2.2 旧版代码 package com.dkl.leanring.spark.ml import org.apache.log4j.{ Level, Logger } import org.apache.spark.{ SparkConf, SparkContext } import org.apache.spark.mllib.regression.LinearRegressionWithSGD import org.apache.spark.mllib.util.MLUtils import org.apache.spark.mllib.regression.LabeledPoint import org.apache.spark.mllib.linalg.Vectors import org.apache.spark.mllib.regression.LinearRegressionModel object OldLinearRegression { def main(args: Array[String]) { // 构建Spark对象 val conf = new SparkConf().setAppName("OldLinearRegression").setMaster("local") val sc = new SparkContext(conf) Logger.getRootLogger.setLevel(Level.WARN) //读取样本数据 val data_path = "files/ml/linear_regression_data3.txt" val training = MLUtils.loadLibSVMFile(sc, data_path) val numTraing = training.count() // 新建线性回归模型,并设置训练参数 val numIterations = 10000 val stepSize = 0.5 val miniBatchFraction = 1.0 //书上的代码 intercept 永远为0 //val model = LinearRegressionWithSGD.train(examples, numIterations, stepSize, miniBatchFraction) var lr = new LinearRegressionWithSGD().setIntercept(true) lr.optimizer.setNumIterations(numIterations).setStepSize(stepSize).setMiniBatchFraction(miniBatchFraction) val model = lr.run(training) println(model.weights) println(model.intercept) // 对样本进行测试 val prediction = model.predict(training.map(_.features)) val predictionAndLabel = prediction.zip(training.map(_.label)) val print_predict = predictionAndLabel.take(20) println("prediction" + "\t" + "label") for (i <- 0 to print_predict.length - 1) { println(print_predict(i)._1 + "\t" + print_predict(i)._2) } // 计算测试误差 val loss = predictionAndLabel.map { case (p, l) => val err = p - l err * err }.reduce(_ + _) val rmse = math.sqrt(loss / numTraing) println(s"Test RMSE = $rmse.") } } 其中注释的第30行代码为书上的写法,但这样写intercept一直为0,也就是只适用于y=a*x的形式,不适用于y=ax+b,改为31、32替代即可。 结果: [0.992894785953067] -0.9446037936869749 prediction label 0.9418962996238525 1.0 2.133370042767533 2.0 3.0269753501252934 3.0 3.473778003804174 3.5 4.039728031797421 4.0 8.954557222265104 9.0 -1.9176406839209805 -2.0 Test RMSE = 0.06866615969192089. 即a=0.992894785953067,b=-0.9446037936869749,y=0.992894785953067*x-0.9446037936869749 2.2 新版代码 package com.dkl.leanring.spark.ml import org.apache.spark.ml.regression.LinearRegression import org.apache.spark.sql.SparkSession object NewLinearRegression { def main(args: Array[String]): Unit = { val spark = SparkSession .builder .appName("NewLinearRegression") .master("local") .getOrCreate() val data_path = "files/ml/linear_regression_data3.txt" import spark.implicits._ import org.apache.spark.ml.linalg.Vectors import org.apache.spark.sql.Row val training = spark.read.format("libsvm").load(data_path) val lr = new LinearRegression() .setMaxIter(10000) .setRegParam(0.3) .setElasticNetParam(0.8) val lrModel = lr.fit(training) println(s"Coefficients: ${lrModel.coefficients} Intercept: ${lrModel.intercept}") val trainingSummary = lrModel.summary println(s"numIterations: ${trainingSummary.totalIterations}") println(s"objectiveHistory: [${trainingSummary.objectiveHistory.mkString(",")}]") trainingSummary.residuals.show() println(s"RMSE: ${trainingSummary.rootMeanSquaredError}") println(s"r2: ${trainingSummary.r2}") trainingSummary.predictions.show() spark.stop() } } 结果: Coefficients: [0.9072296333951224] Intercept: -0.630360819004294 numIterations: 3 objectiveHistory: [0.5,0.41543560544030766,0.08269406021049913] +--------------------+ | residuals| +--------------------+ | -0.0933754844464385| |-0.18205104452058585| |0.001442285423804...| | 0.09318895039599973| | 0.07606805936077965| | 0.5852813740549223| | -0.4805541402684861| +--------------------+ RMSE: 0.2999573166705823 r2: 0.9906296595124621 +-----+---------------+------------------+ |label| features| prediction| +-----+---------------+------------------+ | 1.0| (1,[0],[1.9])|1.0933754844464385| | 2.0| (1,[0],[3.1])| 2.182051044520586| | 3.0| (1,[0],[4.0])|2.9985577145761955| | 3.5| (1,[0],[4.45])|3.4068110496040003| | 4.0| (1,[0],[5.02])|3.9239319406392204| | 9.0| (1,[0],[9.97])| 8.414718625945078| | -2.0|(1,[0],[-0.98])|-1.519445859731514| +-----+---------------+------------------+

优秀的个人博客,低调大师

阿里云聆听快讯,互通之链

阿里云聆听平台上线一年,聆听快讯如时推出,阿里云客户体验大盘展露雏形。 为什么会在现在推出聆听快讯? 也许会有客户说,就是一个快讯页嘛; 也有客户会说,我看到了我的名字,在客户体验之星栏; 还有用户会说,聆听这一年居然做了这么多的事啊,看起来很厉害的样子。 首先,快讯就是窥一斑而知全貌,使客户快速了解阿里云客户体验在一段时间内提供服务的成果及产出。 第二,客户体验不只是获取客户建议、使用问题,进行产品优化改进、解决问题这么简单,还需要与用户互通,与产品及平台互通,做到真正的了解客户需要什么,希望获取什么信息及权益,而这些信息存在客户的认知里,情感上,真实的实用场景里。所以聆听也一直在做互通互动的事,为产品以及各平台搭建桥梁,让阿里云各服务线因聆听而互通。 下面就快速的来了解下聆听快讯都呈现了些什么成果: 共发布12期荣誉榜单,360

优秀的个人博客,低调大师

Android布局优化之ViewStub的使用

背景 最近刚好有看到ViewStub,因此根据个人理解记录下笔记。 ViewStub是Android布局优化的方式之一。 它可以让部分布局延迟加载,从而提高页面渲染速度。 场景 因为ViewStub是用于延迟加载使用,因此适用场景是一些不需要即时展示的页面。 举个例子,大家都用过登录页面。 假设第一次你输入登录用户名和密码错误时,第二次输入会要求你输入验证码。 这里的验证码第一次渲染页面时不需要显示,因此可以适用延迟加载场景。 而像用户名和密码输入框因为第一次显示的时候就要求展示在页面上,因此不适合使用ViewStub。 ViewStub和android:visibility="gone"区别 可能大家会好奇,如果ViewStub的作用是延迟加载。 那么如果我把要延迟加载的布局visibility设置为gone不是一样的效果吗? 表面上看起来效果是一样的,但是区别在哪呢? 设置某个布局模块为gone,但是系统在渲染该布局时还是会去计算这个布局模块的宽高等属性,还是会把它添加到布局树上。因此这个布局模块还是会占有渲染布局的部分时间。 而把该布局模块放在ViewStub,系统在渲染该布局时并不会去理ViewStub节点,因此可以节省渲染布局模块的时间。只有当需要展示时,才会去渲染。 ViewStub使用 正如我们之前所说的,ViewStub下的布局是不会展示的。 那么怎么让它展示呢? 获得ViewStub组件。 跟其他组件一样通过findViewById(R.id.view_stub)获得mViewStub; 显示。 有两种方式: 直接调用mViewStub.setVisibility(View.VISIBLE); 通过inflatemStubView = mViewStub.inflate(); 两种方式的区别在于通过inflate可以返回引用的布局View,可以通过该引用获得布局View的其他组件。 NOTE inflate只能调用一次,不能调用多次,否则会报错。 因为设置ViewStub可见后,ViewStub就不复存在了。 具体示例Demo可以看github Demo。

优秀的个人博客,低调大师

Docker学习之搭建私有镜像仓库

过节之前来一发,又是许久没整理笔记了,今天跟大家聊聊Docker如何搭建私有仓库的几种方式。首先我们来回顾一下之前讲到的Doker 平台的基本构成。 Doker 平台的基本构成 Docker 平台基本上由三部分组成: 客户端:用户使用 Docker 提供的工具(CLI 以及 API 等)来构建,上传镜像并发布命令来创建和启动容器 Docker 主机:从 Docker registry 上下载镜像并启动容器 Docker registry:Docker 镜像仓库,用于保存镜像,并提供镜像上传和下载 后面的文章会具体分析。 搭建方式 与Mavan的管理一样,Docker不仅提供了一个中央仓库,同时也允许我们使用registry搭建本地私有镜像仓库。 使用私有仓库有许多优点: 节省网络带宽,针对于每个镜像不用每个人都去中央仓库上面去下载,只需要从私有仓库中下载即可; 提供镜像资源利用,针对于公司内部使用的镜像,推送到本地的私有仓库中,以供公司内部相关人员使用。 方式一(registry镜像) 环境:为了测试安装方便,这里准备了一台装有Docker的云服务器。 搭建私有仓库: # 下载registry镜像 $ sudo docker pull registry # 通过该镜像启动一个容器 $ sudo docker run -d -p 8082:8082 registry # 映射镜像路径至宿机器、放置容器删除、镜像丢失: $ sudo docker run -d -p 8082:8082 -v /opt/data/registry:/tmp/registry registry 修改配置并重启Docker vi /etc/docker/daemon.json { "registry-mirrors": ["172.17.120.102:8082"], "insecure-registries":["172.17.120.102:8082"] } # 重启 docker 服务 systemctl restart docker 测试仓库Push/Pull: # 首先pull一个比较小的镜像(busybox)来测试 docker pull busybox # 修改一下该镜像的tag $ docker tag busybox 172.17.120.102:8080/busybox # 上传镜像到私有仓库。 $ docker push 172.17.120.102:8082/busybox 到此就搭建好了Docker私有仓库,但是如上搭建的仓库是不需要加密认证的,当然你可以通过证书或者Nginx实现认证访问。下面介绍一下基于Nexus 3搭建的Docker私有仓库。 方式二(Nexus 3) Nexus简介 Nexus是一个多功能的仓库管理系统,是企业常用的私有仓库服务器软件。目前常被用来作为Maven私服、Docker私服。 优点 安装简单,并且有官方Docker镜像 用户界面,并提供REST API 支持浏览、检索以及检查机制 支持npm与bower以及Raw repositories、NuGet repositories 总之Nexus物美价廉,又提供功能全面的oss版,加之支持种类众多的依赖管理,又可以统一管理docker镜像。 安装 参考之前写的一篇博客:本地私服仓库nexus3.3.1使用手册 。当然,这里我们有更简洁的安装方式,由于nexus3+依赖于JDK1.8,可能有不少企业系统上安装的还是1.7甚至是1.6版本,这里我们选择使用Docker镜像安装。 下载安装: # 下载nexus3镜像(pull前请更换镜像加速器,否则可能无法下载) $ sudo docker pull sonatype/nexus3 # 通过该镜像启动一个容器 $ sudo docker run -d -p 8081:8081 -p 8082:8082 --name nexus sonatype/nexus3 # 可能需要一些时间(2-3分钟)才能在新容器中启动该服务。一旦Nexus准备就绪,您可以确定日志以确定结果: $ sudo docker logs -f nexus # 测试 如果出现pong说明启动成功 $ curl -u admin:admin123 http://localhost:8081/service/metrics/ping 注意事项: 可能会出现无法启动的问题,由于云服务器只有1G内存,剩余也有几十MB的样式,显然是无法跑起来的。 Nexus的安装是/opt/sonatype/nexus。 持久目录,/nexus-data用于配置,日志和存储。该目录需要由作为UID 200运行的Nexus进程写入。 环境变量用于将JVM参数传递给启动脚本 $ docker run -d -p 8081:8081 --name nexus -e INSTALL4J_ADD_VM_PARAMS="-Xms2g -Xmx2g -XX:MaxDirectMemorySize=3g -Djava.util.prefs.userRoot=/some-other-dir" sonatype/nexus3 控制Nexus访问目录,NEXUS_CONTEXT,默认为/ docker run -d -p 8081:8081 --name nexus -e NEXUS_CONTEXT=nexus sonatype/nexus3 持久数据 $ mkdir /opt/data/nexus-data && chown -R 200 /opt/data/nexus-data $ docker run -d -p 8081:8081 --name nexus -v /opt/data/nexus-data:/nexus-data sonatype/nexus3 创建本地仓库: Nexus配置: 项目 地址端口 Nexus UI 8081 private repo 8082 URL http://192.168.1.180:8081/ 作者: 小柒2012 欢迎关注: https://blog.52itstyle.com

优秀的个人博客,低调大师

Tomcat架构解析之1 架构简介

Tomcat除了能够支撑通常的web app外,其本身高度模块化的架构体系,也能带来最大限度的可扩展性。 目前tomcat版本已经衍生到tomcat9,但是主流的版本还是tomcat6。此系列架构体系介绍还是以tomcat6为蓝本。 Tomcat是有一系列逻辑模块组织而成,这些模块主要包括: 核心架构模块,例如Server,Service,engine,host和context及wrapper等 网络接口模块connector log模块 session管理模块 jasper模块 naming模块 JMX模块 权限控制模块 …… 这些模块会在相关的文档里逐一描述,本篇文档以介绍核心架构模块为主。 1 核心架构模块说明 核心架构模块之间是层层包含关系。 例如可以说Service是Server的子组件,Server是Service的父组件。 在server.xml已经非常清晰的定义了这些组件之间的关系及配置。 需要强调的是Service中配置了实际工作的Engine,同时配置了用来处理时间业务的线程组Executor(如果没有配置则用系统默认的WorkThread模式的线程组),以及处理网络socket的相关组件connector。详细情况如图所示。 1:n代表一对多的关系;1:1代表一对一的关系 StandEngine, StandHost, StandContext及StandWrapper是容器,他们之间有互相的包含关系。例如,StandEngine是StandHost的父容器,StandHost是StandEngine的子容器。在StandService内还包含一个Executor及Connector。 Executor是线程池,它的具体实现是executor,这个不是必须的,如果没有配置,则使用自写的worker thread线程池 Connector是网络socket相关接口模块,它包含两个对象,ProtocolHandler及Adapter ProtocolHandler是接收socket请求,并将其解析成HTTP请求对象,可以配置成nio模式或者传统io模式 Adapter是处理HTTP请求对象,它就是从StandEngine的valve一直调用到StandWrapper的valve 2 分层建模 一个服务器无非是接受HTTP request,然后处理,产生HTTP response通过原有连接返回给客户端。 那为什么会整出这么多的模块进行处理,这些模块是不是有些多余呢? 其实这些模块各司其职,我们从底层wrapper开始,一直到顶层的server 通过这些描述,会发现这正是tomcat架构的高度模块化的体现。这些细分的模块,使得tomcat非常健壮,通过一些配置和模块定制化,可以很大限度的扩展tomcat。 首先,我们以一个典型的页面访问为例,假设访问的URL是http://www.mydomain.com/app/index.html 详细情况 Wrapper封装了具体的访问资源 index.html Context 封装了各个wrapper资源的集合 app Host 封装了各个context资源的集合 www.mydomain.com 按照领域模型,这个典型的URL访问,可以解析出三层领域对象,他们之间互有隶属关系。这是最基本的建模。 从上面的分析可以看出,从wrapper到host层层递进,层层组合。 那么host 资源的集合是什么呢,就是上面所说的engine。 如果说以上的三个容器可以看成是物理模型的封装,那么engine可以看成是一种逻辑的封装。 有这套engine的支持,我们已经可以完成从engine到host到context再到某个特定wrapper的定位,然后进行业务逻辑的处理 先说线程池,这是典型的线程池的应用。首先从线程池中取出一个可用线程,来处理请求,这个组件就是connector。 它就像酒店的前台服务员登记客人信息办理入住一样,主要完成了HTTP消息的解析,根据tomcat内部的mapping规则,完成从engine到host到context再到某个特定wrapper的定位,进行业务处理,然后将返回结果返回。之后,此次处理结束,线程重新回到线程池中,为下一次请求提供服务。 如果线程池中没有空闲线程,则请求被阻塞,直到有空闲线程进行处理,最多至阻塞超时。 线程池的实现有executor及worker thread(默认) 至此,可以说一个酒店有了前台接待,有了房间等硬件设施,就可以开始正式运营了。 那么把engine,处理线程池,connector封装在一起,形成了一个完整独立的处理单元,这就是service,就好比某个独立的酒店。 通常,我们经常看见某某集团旗下酒店。也就是说,每个品牌有多个酒店同时运营。就好比tomcat中有多个service独自运行。那么这多个service的集合就是server,就好比是酒店所属的集团。 3 作用域 为什么要按层次分别封装一个对象呢?这主要是为了方便统一管理。 类似命名空间的概念,在不同层次的配置,其作用域不一样。 以tomcat自带的打印request与response消息的RequestDumperValve为例。这个valve的类路径org.apache.catalina.valves.RequestDumperValve valve机制是tomcat非常重要的处理逻辑的机制,会在相关文档里专门描述。 如果这个valve配置在server.xml的节点下,则其只打印出访问这个app(my)的request与response消息。 <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <Context path="/my" docBase=" /usr/local/tomcat/backup/my" > <Valve className="org.apache.catalina.valves.RequestDumperValve"/> </Context> <Context path="/my2" docBase=" /usr/local/tomcat/backup/my" > </Context> </Host> 若这个valve配置在server.xml节点下,则可以打印出访问这个host下两个app的request与response信息 <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <Valve className="org.apache.catalina.valves.RequestDumperValve"/> <Context path="/my" docBase=" /usr/local/tomcat/backup/my" > </Context> <Context path="/my2" docBase=" /usr/local/tomcat/backup/my" > </Context> </Host> 在这里贴一个默认的server.xml的配置,通过这些配置可以加深对tomcat核心架构分层模块的理解 <Server port="8005" shutdown="SHUTDOWN"> <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /> <Listener className="org.apache.catalina.core.JasperListener" /> <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" /> <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> <GlobalNamingResources> <Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" /> </GlobalNamingResources> <Service name="Catalina"> <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> <Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="7443" /> <Connector port="7009" protocol="AJP/1.3" redirectPort="7443" /> <Engine name="Catalina" defaultHost="localhost"> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <Context path="/my" docBase="/usr/local/tomcat/backup/my" > </Context> </Host> </Engine> </Service> </Server> 至此,头脑中应该有tomcat整体架构的概念

优秀的个人博客,低调大师

Tomcat架构解析之2 connector BIO

在上文已介绍过,connector组件是service容器中的一部分。 它主要是接收,解析HTTP请求,然后调用本service下的相关Servlet Tomcat从架构上采用的是一个分层结构,因此根据解析过的HTTP请求,定位到相应的Servlet也是一个相对比较复杂的过程 整个Connector实现了从接收 Socket到调用 Servlet的全部过程 先看 Connector的执行逻辑 接收socket 从socket获取数据包,并解析成HttpServletRequest对象 从engine容器开始走调用流程,经过各层valve,最后调用Servlet完成业务逻辑 返回response,关闭socket 可看出,整个Connector组件是Tomcat运行主干,之前介绍的各个模块都是Tomcat启动时,静态创建好的,通过Connector将这些模块串起 网络吞吐一直是整个服务的瓶颈所在,Connector的运行效率在一定程度上影响了Tomcat的整体性能。相对来说,Tomcat在处理静态页面方面一直有一些瓶颈,因此通常的服务架构都是前端类似Nginx的web服务器,后端挂上Tomcat作为应用服务器(当然还有些其他原因,例如负载均衡等) Tomcat在Connector的优化上做了一些特殊的处理,这些都是可选的,通过部署,配置方便完成,例如APR(Apache Portable Runtime),BIO,NIO等 目前Connector支持的协议是HTTP和AJP。 AJP是Apache与其他服务器之间的通信协议。通常在集群环境中,例如前端web服务器和后端应用服务器或servlet容器,使用AJP会比HTTP有更好的性能,这里引述apache官网上的一段话 本篇主要针对HTTP协议的Connector进行阐述 先来看一下Connector配置,在server.xml里 熟悉的80端口不必说了。protocol这里是指这个Connector支持的协议。 具体到HTTP协议,这个属性可以配置的值有 HTTP/1.1 org.apache.coyote.http11.Http11Protocol –BIO实现 org.apache.coyote.http11.Http11NioProtocol –NIO实现 定制的接口 配置HTTP/1.1和org.apache.coyote.http11.Http11Protocol效果一样,因此Connector的HTTP协议实现默认支持BIO的 无论BIO/NIO都是实现一个org.apache.coyote.ProtocolHandler接口,因此如果需要定制,也必须实现这个接口 来看看默认状态下HTTP connector的架构及其消息流 Connector的三大件 HTTP11Protocol Mapper CoyoteAdapter HTTP11Protocol 类全路径org.apache.coyote.http11.Http11Protocol,这是支持HTTP的BIO实现 包含了JIoEndpoint对象及Http11ConnectionHandler对象。 Http11ConnectionHandler对象维护了一个Http11Processor对象池,Http11Processor对象会调用CoyoteAdapter完成http request的解析和分派。 JIoEndpoint维护了两个线程池,Acceptor及Worker。Acceptor是接收socket,然后从Worker线程池中找出空闲的线程处理socket,如果worker线程池没有空闲线程,则Acceptor将阻塞。Worker是典型的线程池实现。Worker线程拿到socket后,就从Http11Processor对象池中获取Http11Processor对象,进一步处理。除了这个比较基础的Worker线程池,也可以通过基于java concurrent 系列的java.util.concurrent.ThreadPoolExecutor线程池实现,不过需要在server.xml中配置相应的节点,即在connector同级别配置<Executor>,配置完后,使用ThreadPoolExecutor与Worker在实现上没有什么大的区别,就不赘述了。 <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> 图中的箭头代表了消息流。 Mapper 类全路径org.apache.tomcat.util.http.mapper.Mapper,此对象维护了一个从Host到Wrapper的各级容器的快照 它主要是为了,当HTTP request被解析后,能够将HTTP request绑定到相应的servlet进行业务处理。前面的文章中已经说明,在加载各层容器时,会将它们注册到JMX中。 所以当 Connector启动,会从JMX中查询出各层容器,然后再创建这个Mapper对象中的快照 CoyoteAdapter 全路径org.apache.catalina.connector.CoyoteAdapter,此对象负责将HTTP request解析成HttpServletRequest对象,之后绑定相应的容器,然后从engine开始逐层调用valve直至该servlet。 在Session管理中,已经说明,根据request中的jsessionid绑定服务器端的相应session。 这个jsessionid按照优先级或是从request url中获取,或是从cookie中获取,然后再session池中找到相应匹配的session对象,然后将其封装到HttpServletRequest对象。所有这些都是在CoyoteAdapter中完成的。 看一下将request解析为HttpServletRequest对象后,开始调用servlet的代码;connector.getContainer().getPipeline().getFirst().invoke(request, response); connector的容器就是StandardEngine,代码的可读性很强,获取StandardEngine的pipeline,然后从第一个valve开始调用逻辑,相应的过程请参照tomcat架构分析(valve机制)。

优秀的个人博客,低调大师

Tomcat架构解析之3 Connector NIO

上文简单记录了默认的Connector的内部构造及消息流,同时此Connector也是基于BIO的实现。 除BIO,也可以通过配置快速部署NIO的connector。在server.xml中如下配置; 整个Tomcat是一个比较完善的框架体系,各组件间都是基于接口实现,方便扩展 像这里的 org.apache.coyote.http11.Http11NioProtocol和BIO的 org.apache.coyote.http11.Http11Protocol都是统一的实现 org.apache.coyote.ProtocolHandler接口 ProtocolHandler的实现类 从整体结构上来说,NIO还是与BIO的实现保持大体一致 NIO connector的内部结构 还是可以看见 Connector中三大件 Http11NioProtocol Mapper CoyoteAdapter 基本功能与BIO的类似 重点看看Http11NioProtocol. 和JIoEndpoint一样, NioEndpoint是 Http11NioProtocol中负责接收处理 socket的主要模块 NioEndpoint的主要流程 Acceptor及 Worker分别是以线程池形式存在 Poller是一个单线程 注意,与BIO的实现一样,默认状态下,在server.xml中 没有配置<Executor>,则以Worker线程池运行 配置了<Executor>,则以基于juc 系列的ThreadPoolExecutor线程池运行。 Acceptor 接收socket线程,这里虽然是基于NIO的connector,但是在接收socket方面还是传统的serverSocket.accept()方式,获得SocketChannel对象 然后封装在一个tomcat的实现类org.apache.tomcat.util.net.NioChannel对象中 然后将NioChannel对象封装在一个PollerEvent对象中,并将PollerEvent对象压入events queue里。这里是个典型的生产者-消费者模式,Acceptor与Poller线程之间通过queue通信,Acceptor是events queue的生产者,Poller是events queue的消费者。 Poller Poller线程中维护了一个Selector对象,NIO就是基于Selector来完成逻辑的 在Connector中并不止一个Selector,在Socket的读写数据时,为了控制timeout也有一个Selector,在后面的BlockSelector中介绍。可以先把Poller线程中维护的这个Selector标为主Selector Poller是NIO实现的主要线程。首先作为events queue的消费者,从queue中取出PollerEvent对象,然后将此对象中的channel以OP_READ事件注册到主Selector中,然后主Selector执行select操作,遍历出可以读数据的socket,并从Worker线程池中拿到可用的Worker线程,然后将socket传递给Worker。整个过程是典型的NIO实现。 Worker Worker线程拿到Poller传过来的socket后,将socket封装在SocketProcessor对象中。然后从Http11ConnectionHandler中取出Http11NioProcessor对象,从Http11NioProcessor中调用CoyoteAdapter的逻辑,跟BIO实现一样。在Worker线程中,会完成从socket中读取http request,解析成HttpServletRequest对象,分派到相应的servlet并完成逻辑,然后将response通过socket发回client。在从socket中读数据和往socket中写数据的过程,并没有像典型的非阻塞的NIO的那样,注册OP_READ或OP_WRITE事件到主Selector,而是直接通过socket完成读写,这时是阻塞完成的,但是在timeout控制上,使用了NIO的Selector机制,但是这个Selector并不是Poller线程维护的主Selector,而是BlockPoller线程中维护的Selector,称之为辅Selector。 NioSelectorPool NioEndpoint对象中维护了一个NioSelecPool对象,这个NioSelectorPool中又维护了一个BlockPoller线程,这个线程就是基于辅Selector进行NIO的逻辑。以执行servlet后,得到response,往socket中写数据为例,最终写的过程调用NioBlockingSelector的write方法。 public int write(ByteBuffer buf, NioChannel socket, long writeTimeout,MutableInteger lastWrite) throws IOException { SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); if ( key == null ) throw new IOException("Key no longer registered"); KeyAttachment att = (KeyAttachment) key.attachment(); int written = 0; boolean timedout = false; int keycount = 1; //assume we can write long time = System.currentTimeMillis(); //start the timeout timer try { while ( (!timedout) && buf.hasRemaining()) { if (keycount > 0) { //only write if we were registered for a write //直接往socket中写数据 int cnt = socket.write(buf); //write the data lastWrite.set(cnt); if (cnt == -1) throw new EOFException(); written += cnt; //写数据成功,直接进入下一次循环,继续写 if (cnt > 0) { time = System.currentTimeMillis(); //reset our timeout timer continue; //we successfully wrote, try again without a selector } } //如果写数据返回值cnt等于0,通常是网络不稳定造成的写数据失败 try { //开始一个倒数计数器 if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1); //将socket注册到辅Selector,这里poller就是BlockSelector线程 poller.add(att,SelectionKey.OP_WRITE); //阻塞,直至超时时间唤醒,或者在还没有达到超时时间,在BlockSelector中唤醒 att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS); }catch (InterruptedException ignore) { Thread.interrupted(); } if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) { keycount = 0; }else { //还没超时就唤醒,说明网络状态恢复,继续下一次循环,完成写socket keycount = 1; att.resetWriteLatch(); } if (writeTimeout > 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= writeTimeout; } //while if (timedout) throw new SocketTimeoutException(); } finally { poller.remove(att,SelectionKey.OP_WRITE); if (timedout && key != null) { poller.cancelKey(socket, key); } } return written; } 也就是说当socket.write()返回0时,说明网络状态不稳定,这时将socket注册OP_WRITE事件到辅Selector,由BlockPoller线程不断轮询这个辅Selector,直到发现这个socket的写状态恢复了,通过那个倒数计数器,通知Worker线程继续写socket动作。 看一下BlockSelector线程的逻辑; public void run() { while (run) { try { ...... Iterator iterator = keyCount > 0 ? selector.selectedKeys().iterator() : null; while (run && iterator != null && iterator.hasNext()) { SelectionKey sk = (SelectionKey) iterator.next(); KeyAttachment attachment = (KeyAttachment)sk.attachment(); try { attachment.access(); iterator.remove(); ; sk.interestOps(sk.interestOps() & (~sk.readyOps())); if ( sk.isReadable() ) { countDown(attachment.getReadLatch()); } //发现socket可写状态恢复,将倒数计数器置位,通知Worker线程继续 if (sk.isWritable()) { countDown(attachment.getWriteLatch()); } }catch (CancelledKeyException ckx) { if (sk!=null) sk.cancel(); countDown(attachment.getReadLatch()); countDown(attachment.getWriteLatch()); } }//while }catch ( Throwable t ) { log.error("",t); } } events.clear(); try { selector.selectNow();//cancel all remaining keys }catch( Exception ignore ) { if (log.isDebugEnabled())log.debug("",ignore); } } 使用这个辅Selector主要是减少线程间的切换,同时还可减轻主Selector的负担。以上描述了NIO connector工作的主要逻辑,可以看到在设计上还是比较精巧的。NIO connector还有一块就是Comet,有时间再说吧。需要注意的是,上面从Acceptor开始,有很多对象的封装,NioChannel及其KeyAttachment,PollerEvent和SocketProcessor对象,这些不是每次都重新生成一个新的,都是NioEndpoint分别维护了它们的对象池; ConcurrentLinkedQueue<SocketProcessor> processorCache = new ConcurrentLinkedQueue<SocketProcessor>() ConcurrentLinkedQueue<KeyAttachment> keyCache = new ConcurrentLinkedQueue<KeyAttachment>() ConcurrentLinkedQueue<PollerEvent> eventCache = new ConcurrentLinkedQueue<PollerEvent>() ConcurrentLinkedQueue<NioChannel> nioChannels = new ConcurrentLinkedQueue<NioChannel>() 当需要这些对象时,分别从它们的对象池获取,当用完后返回给相应的对象池,这样可以减少因为创建及GC对象时的性能消耗

优秀的个人博客,低调大师

IPV6之ECS初尝试

背景信息: 自从苹果审核要求app支持ipv6的通讯以来,有很多工单咨询ipv6如何设置,今天基于Centos 6.8 64位系统搭建一下ipv6的演示环境,欢迎斧正 确认ipv6是否安装: 1.使用ifconfig命令查看网络信息是否有ipv6的信息 eth0 Link encap:Ethernet HWaddr 00:16:3E:32:A2:3E inet addr:172.30.191.179 Bcast:172.30.255.255 Mask:255.255.0.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:249646 errors:0 dropped:0 over

优秀的个人博客,低调大师

Java8-Stream之数值流

在Stream里元素都是对象,那么,当我们操作一个数字流的时候就不得不考虑一个问题,拆箱和装箱。虽然自动拆箱不需要我们处理,但依旧有隐含的成本在里面。Java8引入了3个原始类型特化流接口来解决这个问题:IntStream,DoubleStream,LongStream, 分别将流中的元素特化为int、long、doub,从而避免了暗含的装箱成本。每个接口都带来了进行常用数值归约的新方法,比如求和sum,求最大值max。此外还有必要时再把他们转换回对象流的方法。这些特化的原因就是装箱造成的复杂性--类似int和Integer之间的效率差异。 将对象流映射为数值流 常用方法为mapToInt, mapToDouble, mapToLong,这些方法和map相同,只是它们返回一个特化流,而不是Stream。 @Test public void testToInt() { final ArrayList<Dish> dishes = Lists.newArrayList( new Dish("pork", false, 800, Type.MEAT), new Dish("beef", false, 700, Type.MEAT), new Dish("chicken", false, 400, Type.MEAT), new Dish("french fries", true, 530, Type.OTHER), new Dish("rice", true, 350, Type.OTHER), new Dish("season fruit", true, 120, Type.OTHER), new Dish("pizza", true, 550, Type.OTHER), new Dish("prawns", false, 300, Type.FISH), new Dish("salmon", false, 450, Type.FISH) ); IntStream intStream = dishes.stream() .mapToInt(Dish::getCalories); } 将数值流转回对象流 我们虽然会使用数值流进行计算,但经常需要回归到对象,那么就需要将int stream装箱为Integer stream. 可以使用boxed()方法。 Stream<Integer> boxed = intStream.boxed(); 默认值OptinalInt 由于数值流经常会有默认值,比如默认为0。数值特化流的终端操作会返回一个OptinalXXX对象而不是数值。 OptionalInt optionalInt = dishes.stream() .mapToInt(Dish::getCalories) .max(); int max = optionalInt.orElse(1); 生成一个数值范围流 有时候需要生成一个数值范围,比如1到30. 可以使用for循环,也可以直接使用数值流。 创建一个包含两端的数值流,比如1到10,包含10: IntStream intStream = IntStream.rangeClosed(1, 10); 创建一个不包含结尾的数值流,比如1到9: IntStream range = IntStream.range(1, 9); 注 测试demo: https://github.com/Ryan-Miao/someTest/blob/master/src/main/java/com/test/java8/streams/NumStreamExample.java 以上出自《Java8 In Action》 关注我的公众号 唯有不断学习方能改变! -- Ryan Miao

资源下载

更多资源
腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码