首页 文章 精选 留言 我的

精选列表

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

Netty深入浅出(一)入门

传统Socket中,NIO和IO的比较(Nio知识回顾) IO 阻塞点: server.accept(); 和 单线程情况下只能有一个客户端 用线程池可以有多个客户端连接,但是非常消耗性能 NIO selector.select()会产生阻塞的效果,但是它其实是非阻塞的 为什么呢? selector.select(1000); 1s检测一次 selector.wakeup(); 唤醒selector 可以任由我们控制休眠和唤醒操作,所以它其实是非阻塞型 要想更加了解NIO,请查看我的NIO专题 什么是netty netty可以运用在那些领域? 1分布式进程通信 例如: hadoop、dubbo、akka等具有分布式功能的框架,底层RPC通信都是基于netty实现的,这些框架使用的版本通常都还在用netty3.x 2、游戏服务器开发 最新的游戏服务器有部分公司可能已经开始采用netty4.x 或 netty5.x 1、netty服务端hello world案例 1. 创建Server类 package com.netty; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.string.StringDecoder; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Fant.J. * 2018/2/2 21:28 */ public class Server { public static void main(String[] args) { //服务类 ServerBootstrap bootstrap = new ServerBootstrap(); //两个线程池 ExecutorService booss = Executors.newCachedThreadPool(); ExecutorService worker = Executors.newCachedThreadPool(); //设置niosocket工厂 bootstrap.setFactory(new NioServerSocketChannelFactory(booss,worker)); //设置管道工厂 bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); //将网络传输中的字节码(ChannelBuffer) 转换成String 可看源码 pipeline.addLast("decoder",new StringDecoder()); //将管道交给HelloHandler处理 pipeline.addLast("helloHandler",new HelloHandler()); return pipeline; } }); bootstrap.bind(new InetSocketAddress(10101)); System.out.println("server start"); } } 2. 创建HelloHandler类 需要继承SimpleChannelHandler类,然后重写几个基本方法 messageReceived() 接受消息 exceptionCaught() 捕获异常 channelConnected() 建立连接 channelDisconnected() 断开连接:必须是连接已经建立,关闭通道的时候才会触发。 channelClosed() 关闭通道 package com.netty; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.*; /** * 接受消息 * Created by Fant.J. * 2018/2/2 22:54 */ public class HelloHandler extends SimpleChannelHandler{ /** * Invoked when a message object (e.g: {@link ChannelBuffer}) was received * from a remote peer. * 接受消息 * @param ctx * @param e */ @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { // int i = 1/0; // System.out.println("messageReceived()"); // ChannelBuffer message = (ChannelBuffer) e.getMessage(); // String s = new String(message.array()); System.out.println(e.getMessage()); // System.out.println(s); //回复数据 ChannelBuffer channelBuffer = ChannelBuffers.copiedBuffer("hi".getBytes()); ctx.getChannel().write(channelBuffer); super.messageReceived(ctx, e); } /** * Invoked when an exception was raised by an I/O thread or a * {@link ChannelHandler}. * 捕获异常 * @param ctx * @param e */ @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { System.out.println("exceptionCaught()"); super.exceptionCaught(ctx, e); } /** * Invoked when a {@link Channel} is open, bound to a local address, and * connected to a remote address. * 建立连接 * @param ctx * @param e */ @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { System.out.println("channelConnected() "); super.channelConnected(ctx, e); } /** * Invoked when a {@link Channel} was disconnected from its remote peer. * 断开连接:必须是连接已经建立,关闭通道的时候才会触发。 * @param ctx * @param e */ @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { System.out.println("channelDisconnected()"); super.channelDisconnected(ctx, e); } /** * Invoked when a {@link Channel} was closed and all its related resources * were released. * 关闭通道 * @param ctx * @param e */ @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { System.out.println("channelClosed()"); super.channelClosed(ctx, e); } } 因为网络之间传输是通过字节来传输,所以我们在messageReceived()方法里,获取到的message需要对其进行String转换。转换方法: //先拿到message对应的channelbuffer对象 ChannelBuffer message = (ChannelBuffer) e.getMessage(); String s = new String(message.array()); 同样,我们如果想要回复数据,也要将String转换成字节,这是实例中的一个例子: //前面管道的实例化 这里省略,直接贴出给管道进行StringDecoder()处理代码 pipeline.addLast("decoder",new StringDecoder()); 让我们来研究下原理,其实是这样转换的: //创建一个ChannelBuffer对象,并赋值 字节 ChannelBuffer channelBuffer = ChannelBuffers.copiedBuffer("hi".getBytes()); //获取到Channel并执行write()方法 ctx.getChannel().write(channelBuffer); github路径:https://github.com/jiaofanting/Java-nio-and-netty-spring-demo/tree/master/src/com/netty 2、netty客户端hello world案例 Client类 package com.netty.client; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; import java.net.InetSocketAddress; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Fant.J. * 2018/2/3 10:59 */ public class Client { public static void main(String []args){ //服务类 ClientBootstrap bootstrap = new ClientBootstrap(); //线程池 ExecutorService boss = Executors.newCachedThreadPool(); ExecutorService worker = Executors.newCachedThreadPool(); //socket工厂 bootstrap.setFactory(new NioClientSocketChannelFactory(boss,worker)); //管道工厂 bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder",new StringDecoder()); pipeline.addLast("encoder",new StringEncoder()); pipeline.addLast("hiHandler",new HiHandler()); return pipeline; } }); //连接服务器 ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1",10101)); Channel channel = connect.getChannel(); System.out.println("client start"); Scanner scanner = new Scanner(System.in); while (true){ System.out.println("please input string"); channel.write(scanner.next()); } } } HiHandler类 package com.netty.client; import org.jboss.netty.channel.*; /** * 消息接受处理器 * Created by Fant.J. * 2018/2/3 10:59 */ public class HiHandler extends SimpleChannelHandler{ /** * 接收消息 */ @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String s = (String) e.getMessage(); System.out.println(s); super.messageReceived(ctx, e); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { System.out.println("exceptionCaught()"); super.exceptionCaught(ctx, e); } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { System.out.println("channelOpen()"); super.channelOpen(ctx, e); } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { System.out.println("channelConnected()"); super.channelConnected(ctx, e); } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { System.out.println("channelDisconnected()"); super.channelDisconnected(ctx, e); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { System.out.println("channelClosed()"); super.channelClosed(ctx, e); } }

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

SpringBoot入门系列: Spring Boot的测试

Spring Boot的测试,和普通项目的测试类同,可以继续使用我们熟悉的测试工具。当然,这里的测试,主要还是后台代码的测试。 主要需要注意的地方仅有三点: 1、依赖包的引入:pom.xml中仅依赖spring-boot-starter-test,它把相关的依赖全部引入。 2、在测试类上的注解,常用的注解有三个 @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration 这三个注解,只要注意第二个注解括号内的Application.class就行,把它替换为项目的启动类即可。 我们前面spring-boot-sample-mysql工程的启动类为SpringBootSampleMysqlApplication,那么测试类上的注解就是 @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringBootSampleMysqlApplication.class) @WebAppConfiguration 3、测试类的文件结构,保持src/test/java和src/main/java结构一直,即:包+文件夹。 如:com.example包service中类的测试,那么在src/test/java也是建立com.example包,再在包下建立文件夹service. 注:由于我们测试的启动类用的是项目的启动类,所以Spring Boot项目的测试配置文件任然用src/main/resources的。 下面贴两个个测试类代码 1、服务类的 [java]view plaincopy packagecom.example.service; importjava.util.List; importorg.junit.Assert; importorg.junit.Test; importorg.junit.runner.RunWith; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.boot.test.SpringApplicationConfiguration; importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner; importorg.springframework.test.context.web.WebAppConfiguration; importcom.example.Application; importcom.example.domain.TestPOJO; importcom.example.dto.HotelDto; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes=Application.class) @WebAppConfiguration publicclassTestServicesTest{ @Autowired TestServicestestServices; @Test publicvoidtestShow(){ StringexpectedResult="helloworld!"; Stringresult=testServices.show(); Assert.assertTrue("数据一致",expectedResult.equals(result)); Assert.assertFalse("数据不一致",!expectedResult.equals(result)); } @Test publicvoidtestShowDao(){ List<TestPOJO>testPOJOList=testServices.showDao(10); Assert.assertTrue("数据集不对",testPOJOList.size()==1); Assert.assertTrue("数据一致",testPOJOList.get(0).getName().equals("nice")); } @Test publicvoidtestFindByCountry(){ List<HotelDto>testPOJOList=testServices.findByCountry("US"); Assert.assertTrue("数据集不对",testPOJOList.size()==1); Assert.assertTrue("数据一致",testPOJOList.get(0).getCityName().equals("SanFrancisco")); } } 2、controller类的 [java]view plaincopy packagecom.example.controller; importjava.util.List; importorg.junit.Assert; importorg.junit.Before; importorg.junit.Test; importorg.junit.runner.RunWith; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.boot.test.SpringApplicationConfiguration; importorg.springframework.http.MediaType; importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner; importorg.springframework.test.context.web.WebAppConfiguration; importorg.springframework.test.web.servlet.MockMvc; importorg.springframework.test.web.servlet.MvcResult; importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders; importorg.springframework.test.web.servlet.setup.MockMvcBuilders; importorg.springframework.web.context.WebApplicationContext; importcom.example.Application; importcom.example.domain.TestPOJO; importcom.example.dto.HotelDto; importcom.example.service.TestServices; importcom.fasterxml.jackson.core.JsonProcessingException; importcom.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes=Application.class) @WebAppConfiguration publicclassTestControllerTest{ MockMvcmvc; @Autowired WebApplicationContextwebApplicationConnect; @Autowired TestServicestestServices; StringexpectedJson; @Before publicvoidsetUp()throwsJsonProcessingException{ mvc=MockMvcBuilders.webAppContextSetup(webApplicationConnect).build(); } @Test publicvoidtestShow()throwsException{ StringexpectedResult="helloworld!"; Stringuri="/show"; MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)) .andReturn(); intstatus=mvcResult.getResponse().getStatus(); Stringcontent=mvcResult.getResponse().getContentAsString(); Assert.assertTrue("错误,正确的返回值为200",status==200); Assert.assertFalse("错误,正确的返回值为200",status!=200); Assert.assertTrue("数据一致",expectedResult.equals(content)); Assert.assertFalse("数据不一致",!expectedResult.equals(content)); } protectedStringObj2Json(Objectobj)throwsJsonProcessingException{ ObjectMappermapper=newObjectMapper(); returnmapper.writeValueAsString(obj); } @Test publicvoidtestShowDaoInt()throwsException{ List<TestPOJO>testPOJOList=testServices.showDao(10); expectedJson=Obj2Json(testPOJOList); Stringuri="/showDao?age=10"; MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)).andReturn(); intstatus=mvcResult.getResponse().getStatus(); Stringcontent=mvcResult.getResponse().getContentAsString(); Assert.assertTrue("错误,正确的返回值为200",status==200); Assert.assertFalse("错误,正确的返回值为200",status!=200); Assert.assertTrue("数据一致",expectedJson.equals(content)); Assert.assertFalse("数据不一致",!expectedJson.equals(content)); } @Test publicvoidtestShowDaoString()throwsException{ List<HotelDto>hotelDtoList=testServices.findByCountry("US"); expectedJson=Obj2Json(hotelDtoList); Stringuri="/country/US"; MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)).andReturn(); intstatus=mvcResult.getResponse().getStatus(); Stringcontent=mvcResult.getResponse().getContentAsString(); Assert.assertTrue("错误,正确的返回值为200",status==200); Assert.assertFalse("错误,正确的返回值为200",status!=200); Assert.assertTrue("数据一致",expectedJson.equals(content)); Assert.assertFalse("数据不一致",!expectedJson.equals(content)); } } controller类的,为了MockMvc,注入了WebApplicationContext。 原文地址http://www.bieryun.com/833.html

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

开发VS2008 AddIn 入门Sample

本文主要介绍的是VS2008插件开发 环境要求:VS2008;.Net3.5 目标:开发插件功能为“在VS中创建文本文档,并在文本开头输入//This code was createdFor Testing” 1,Create new project(Visual Studio Add-In) 2,按照wizard一步一步操作: 选择使用C#编写Addin 选择在.NET IDE 和Macro IDE中都可以使用AddIn 输入name和description 选中确定需要AddIn在Tool中显示 选择需要About Information summary Finish 生成solution 此时debug(F5)这个solution,会跳出另外一个VS2008窗口,并且你会发现在Tool工具栏下有^-^笑脸: 3 将Connect类中的Exec方法改为: 代码 4 在connect类中增加方法: 代码 5 build and debug 当按下Tool中的AddIn工具时候会发现文本已经创建,并且文字也已经加入到文本中: 至此,VS AddIn开发完成。 PS:本文示例参考:http://www.c-sharpcorner.com/uploadfile/mgold/addins11292005015631am/addins.aspx 本文转自轩脉刃博客园博客,原文链接:http://www.cnblogs.com/yjf512/archive/2010/06/05/1752401.html,如需转载请自行联系原作者

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

Java正则系列: (1)入门教程

本文简要介绍Java的正则表达式及其实现方式,并通过实例讲解正则表达式的具体用法。 1. 正则表达式 1.1. 简介 正则表达式(Regular Expression), 简称 正则, 也翻译为 正规式, 用来表示文本搜索模式。英文缩写是 regex(reg-ex). 搜索模式(search pattern)可能多种多样, 如, 单个字符(character), 特定字符串(fixed string), 包含特殊含义的复杂表达式等等. 对于给定的字符串, 正则表达式可能匹配一到多次, 也可能一次都不匹配。 正则表达式一般用来查找、编辑和替换文本(text), 本质上, text(文本) 和 string(字符串) 是一回事。 用正则表达式来分析/修改文本的过程, 称为: 应用于文本/字符串的正则表达式 。正则表达式扫描字符串的顺序是从左到右. 每个字符都只能被匹配成功一次, 下次匹配扫描就会从后面开始。例如, 正则表达式 aba, 匹配字符串 ababababa 时, 只会扫描到两个匹配(aba_aba__)。 1.2. 示例 最简单的例子是字母串。例如, 正则表达式 Hello World 能匹配的就是字符串 “Hello World”。 正则表达式中, 点号 .(dot,英文句号)属于通配符, 点号匹配任意一个字符(character); 例如, “a” 或者 “1”; 当然, 默认情况下点号不能匹配换行 \n, 需要特殊标识指定才行。 下表列举了一些简单的正则表达式,和对应的匹配模式。 正则表达式 Matches this is text 完全匹配 “this is text” this\s+is\s+text 匹配的内容为: “this”, 加上1到多个空白符(whitespace character, 如空格,tab,换行等), 加上 “is”, 加上1到多个空白符, 再加上 “text”. ^\d+(\.\d+)? 正则表达式以转义字符 ^(小尖号)打头, 表示这行必须以小尖号后面的字符模式开始, 才会达成匹配. \d+ 匹配1到多个数字. 英文问号 ? 表示可以出现 0~1次. \. 匹配的是字符 “.”, 小括号(parentheses) 表示一个分组. 所以这个正则表达式可以匹配正整数或者小数,如: “5”, “66.6” 或者 “5.21” 等等. 说明,中文的全角空格( )字符不属于空白字符(whitespace characters), 可以认为其属于一个特殊的汉字。 1.3. 编程语言对正则表达式的支持 大多数编程语言都支持正则表达式, 如 Java、Perl, Groovy 等等。但各种语言的正则表达式写法略有一些不同。 2. 预备知识 本教程要求读者具备Java语言相关的基础知识。 下面的一些示例通过 JUnit 来验证执行结果。如果不想使用JUnit, 也可以改写相关代码。关于JUnit的知识请参考 JUnit教程: http://www.vogella.com/tutorials/JUnit/article.html。 3. 语法规则 本章介绍各种正则元素的范本, 我们会先介绍什么是元字符(meta character)。 3.1. 通用表达式简介 正则表达式 说明 . 点号(.), 匹配任意一个字符 ^regex 小尖号(^), 起始标识, 前面不能出现其他字符. regex$ 美元符号($,dollar,美刀), 结束标识,后面不能再出现其他字符. [abc] 字符组(set), 匹配 a 或 b 或 c. [abc][vz] 字符组(set), 匹配 a 或 b 或 c,紧接着是 v 或 z. [^abc] 如果小尖号(^, caret, 此处读作 非) 出现在中括号里面的第一位, 则表示否定(negate). 这里匹配: 除 a, b, c 之外的其他任意字符. [a-d1-7] 范围表示法: 匹配 a 到 d 之间的单个字符, 或者 1 到 7之间的单个字符, 整体只匹配单个字符, 而不是 d1 这种组合. X|Z 匹配 X 或者 Z. XZ 匹配XZ, X和Z必须按顺序全部出现. $ 判断一行是否结束. 3.2. 元字符 下面这些是预定义的元字符(Meta characters), 可用于提取通用模式, 如 \d 可以代替 [0-9], 或者[0123456789]。 正则表达式 说明 \d 单个数字, 等价于 [0-9] 但更简洁 \D 非数字, 等价于 [^0-9] 但更简洁 \s 空白字符(whitespace), 等价于 [ \t\n\x0b\r\f] \S 非空白字符, 等价于 [^\s] \w 反斜线加上小写w, 表示单个标识符,即字母数字下划线, 等价于 [a-zA-Z_0-9] \W 非单词字符, 等价于 [^\w] \S+ 匹配1到多个非空白字符 \b 匹配单词外边界(word boundary), 单词字符指的是 [a-zA-Z0-9_] 这些元字符主要取自于对应单词的英文首字母, 例如: digit(数字), space(空白), word (单词), 以及 boundary(边界)。对应的大写字符则用来表示取反。 3.3. 量词 量词(Quantifier)用来指定某个元素可以出现的次数。?, *, + 和 {} 等符号定义了正则表达式的数量。 正则表达式 说明 示例 * 0到多次, 等价于 {0,} X* 匹配0到多个连续的X, .* 则匹配任意字符串 + 1到多次, 等价于 {1,} X+ 匹配1到多个连续的X ? 0到1次, 等价于 {0,1} X? 匹配0个,后者1个X {n} 精确匹配 n 次 {} 前面序列出现的次数 \d{3} 匹配3位数字, .{10} 匹配任意10个字符. {m, n} 出现 m 到 n 次, \d{1,4} 匹配至少1位数字,至多4位数字. *? 在量词后面加上 ?, 表示懒惰模式(reluctant quantifier). 从左到右慢慢扫描, 找到第一个满足正则表达式的地方就暂停搜索, 用来尝试匹配最少的字符串. 3.4. 分组和引用 可以对正则表达式进行分组(Grouping), 用圆括号 () 括起来。这样就可以对括号内的整体使用量词。 当然, 在进行替换的时候, 还可以对分组进行引用。也就是捕获组(captures the group)。向后引用(back reference) 指向匹配中该分组所对应的字符串。进行替换时可以通过 $ 来引用。 使用 $ 来引用一个捕获组。例如 $1 表示第一组, $2 表示第二组, 以此类推, $0则表示整个正则所匹配的部分。 例如, 想要去掉单词后面, 句号/逗号(point or comma)前面的空格。可以把句号/逗号写入正则中, 然后原样输出到结果中即可。 // 去除单词与 `.|,` 之间的空格 String pattern = "(\\w)(\\s+)([\\.,])"; System.out.println(EXAMPLE_TEST.replaceAll(pattern, "$1$3")); 提取 标签的内容: // 提取 <title> 标签的内容 pattern = "(?i)(<title.*?>)(.+?)()"; String updated = EXAMPLE_TEST.replaceAll(pattern, "$2"); 3.5. 环视 环视(lookaround), 分为顺序环视(Lookahead)与逆序环视(lookbehind), 属于零宽度断言(zero-length assertion)。 类似于行起始标识(^)和结束标识($); 或者单词边界(\b)一类的位置标识。 顺序否定环视(Negative look ahead), 用于在匹配的同时, 排除掉某些情形。也就是说其后面不能是符合某种特征的字符串。 顺序否定环视(Negative look ahead) 使用 (?!pattern) 这种格式定义。例如, 下面的正则, 只匹配后面不是 b 字母的 “a” 字母。 a(?!b) 类似的, 顺序环视(look ahead), 也叫顺序肯定环视。 如,只匹配a字母, 但要求后面只能是 b 字母, 否则这个 a 就不符合需要: a(?=b) 注意,环视 是一种向前/后查找的语法: (?=exp), 会查找后面位置的 exp; 所环视的内容却不包含在正则表达式匹配中。 环视(lookaround)是一种高级技巧, 环视的部分不会匹配到结果之中, 但却要求匹配的字符串前面/后面具备环视部分的特征。 如果将等号换成感叹号, 就是环视否定 (?!exp), 变成否定语义,也就是说查找的位置的后面不能是exp。 逆序肯定环视, (?<=exp), 表示所在位置左侧能够匹配 exp 逆序否定环视, (?<!exp), 表示所在位置左侧不能匹配 exp 详情请参考: 正则应用之——逆序环视探索: http://blog.csdn.net/lxcnn/article/details/4954134 参考: 利用正则表达式排除特定字符串 http://www.cnblogs.com/wangqiguo/archive/2012/05/08/2486548.html 3.6. 正则表达式的模式 在正则表达式开头可以指定模式修饰符(mode modifier)。还可以组合多种模式, 如 (?is)pattern。 (?i) 正则表达式匹配时不区分大小写。 (?s) 单行模式(single line mode), 使点号(.) 匹配所有字符, 包括换行(\n)。 (?m) 多行模式(multi-line mode), 使 小尖号(^,caret) 和 美元符号($, dollar) 匹配目标字符串中每一行的开始和结束。 3.7. Java中的反斜杠 在Java字符串中, 反斜杠(\, backslash) 是转义字符, 有内置的含义。在源代码级别, 需要使用两个反斜杠\\来表示一个反斜杠字符。如果想定义的正则表达式是 \w, 在 .java 文件源码中就需要写成 \\w。 如果想要匹配文本中的1个反斜杠, 则源码中需要写4个反斜杠 \\\\。 4. String类正则相关的方法 4.1. String 类重新定义了正则相关的方法 Java中 String 类内置了4个支持正则的方法, 即: matches(), split(), replaceFirst() 和replaceAll() 方法。 需要注意, replace() 是纯字符串替换, 不支持正则表达式。 这些方法并没有对性能进行优化。稍后我们将讨论优化过的类。 方法 说明 s.matches("regex") 判断字符串 s 是否能匹配正则 "regex". 只有整个字符串匹配正则才返回 true . s.split("regex") 用正则表达式 "regex" 作为分隔符来拆分字符串, 返回结果是 String[] 数组. 注意 "regex" 对应的分隔符并不包含在返回结果中. s.replaceFirst("regex", "replacement") 替换第一个匹配 "regex" 的内容为 "replacement. s.replaceAll("regex", "replacement") 将所有匹配 "regex" 的内容替换为 "replacement. 下面是对应的示例。 package de.vogella.regex.test; public class RegexTestStrings { public static final String EXAMPLE_TEST = "This is my small example " + "string which I'm going to " + "use for pattern matching."; public static void main(String[] args) { System.out.println(EXAMPLE_TEST.matches("\\w.*")); String[] splitString = (EXAMPLE_TEST.split("\\s+")); System.out.println(splitString.length);// should be 14 for (String string : splitString) { System.out.println(string); } // 将所有空白符(whitespace) 替换为 tab System.out.println(EXAMPLE_TEST.replaceAll("\\s+", "\t")); } } 4.2. 示例 下面给出一些正则表达式的使用示例。请参照注释信息。 If you want to test these examples, create for the Java project de.vogella.regex.string. 如果想测试这些示例, 请将java文件放到一个Java包下, 如 de.vogella.regex.string。 package de.vogella.regex.string; public class StringMatcher { // 如果字符串完全匹配 "`true`", 则返回 true public boolean isTrue(String s){ return s.matches("true"); } // 如果字符串完全匹配 "`true`" 或 "`True`", 则返回 true public boolean isTrueVersion2(String s){ return s.matches("[tT]rue"); } // 如果字符串完全匹配 "`true`" 或 "`True`" // 或 "`yes`" 或 "`Yes`", 则返回 true public boolean isTrueOrYes(String s){ return s.matches("[tT]rue|[yY]es"); } // 如果包含字符串 "`true`", 则返回 true public boolean containsTrue(String s){ return s.matches(".*true.*"); } // 如果包含3个字母, 则返回 true public boolean isThreeLetters(String s){ return s.matches("[a-zA-Z]{3}"); // 当然也等价于下面这种比较土的方式 // return s.matches("[a-Z][a-Z][a-Z]"); } // 如果不以数字开头, 则返回 true public boolean isNoNumberAtBeginning(String s){ // 可能 "^\\D.*" 更好一点 return s.matches("^[^\\d].*"); } // 如果包含了 `b` 之外的字符, 则返回 true public boolean isIntersection(String s){ return s.matches("([\\w&&[^b]])*"); } // 如果包含的某串数字小于300, 则返回 true public boolean isLessThenThreeHundred(String s){ return s.matches("[^0-9]*[12]?[0-9]{1,2}[^0-9]*"); } } And a small JUnit Test to validates the examples. 我们通过 JUnit 测试来验证。 package de.vogella.regex.string; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class StringMatcherTest { private StringMatcher m; @Before public void setup(){ m = new StringMatcher(); } @Test public void testIsTrue() { assertTrue(m.isTrue("true")); assertFalse(m.isTrue("true2")); assertFalse(m.isTrue("True")); } @Test public void testIsTrueVersion2() { assertTrue(m.isTrueVersion2("true")); assertFalse(m.isTrueVersion2("true2")); assertTrue(m.isTrueVersion2("True"));; } @Test public void testIsTrueOrYes() { assertTrue(m.isTrueOrYes("true")); assertTrue(m.isTrueOrYes("yes")); assertTrue(m.isTrueOrYes("Yes")); assertFalse(m.isTrueOrYes("no")); } @Test public void testContainsTrue() { assertTrue(m.containsTrue("thetruewithin")); } @Test public void testIsThreeLetters() { assertTrue(m.isThreeLetters("abc")); assertFalse(m.isThreeLetters("abcd")); } @Test public void testisNoNumberAtBeginning() { assertTrue(m.isNoNumberAtBeginning("abc")); assertFalse(m.isNoNumberAtBeginning("1abcd")); assertTrue(m.isNoNumberAtBeginning("a1bcd")); assertTrue(m.isNoNumberAtBeginning("asdfdsf")); } @Test public void testisIntersection() { assertTrue(m.isIntersection("1")); assertFalse(m.isIntersection("abcksdfkdskfsdfdsf")); assertTrue(m.isIntersection("skdskfjsmcnxmvjwque484242")); } @Test public void testLessThenThreeHundred() { assertTrue(m.isLessThenThreeHundred("288")); assertFalse(m.isLessThenThreeHundred("3288")); assertFalse(m.isLessThenThreeHundred("328 8")); assertTrue(m.isLessThenThreeHundred("1")); assertTrue(m.isLessThenThreeHundred("99")); assertFalse(m.isLessThenThreeHundred("300")); } } 5. Pattern与Matcher简介 For advanced regular expressions the java.util.regex.Pattern and java.util.regex.Matcher classes are used. 要支持正则表达式的高级特性, 需要借助 java.util.regex.Pattern 和 java.util.regex.Matcher 类。 首先创建/编译 Pattern 对象, 用来定义正则表达式。对 Pattern 对象, 给定一个字符串, 则产生一个对应的 Matcher 对象。通过 Matcher 对象就可以对 String 进行各种正则相关的操作。 package de.vogella.regex.test; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexTestPatternMatcher { public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching."; public static void main(String[] args) { Pattern pattern = Pattern.compile("\\w+"); // 如需忽略大小写, 可以使用: // Pattern pattern = Pattern.compile("\\w+", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(EXAMPLE_TEST); // 查找所有匹配的结果 while (matcher.find()) { System.out.print("Start index: " + matcher.start()); System.out.print(" End index: " + matcher.end() + " "); System.out.println(matcher.group()); } // 将空格替换为 tabs Pattern replace = Pattern.compile("\\s+"); Matcher matcher2 = replace.matcher(EXAMPLE_TEST); System.out.println(matcher2.replaceAll("\t")); } } 6. 正则表达式示例 下面列出了常用的正则表达式使用情景。希望读者根据实际情况进行适当的调整。 6.1 或(Or) 任务: 编写正则表达式, 用来匹配包含单词 “Joe” 或者 “Jim” , 或者两者都包含的行。 创建 de.vogella.regex.eitheror 包和下面的类。 package de.vogella.regex.eitheror; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class EitherOrCheck { @Test public void testSimpleTrue() { String s = "humbapumpa jim"; assertTrue(s.matches(".*(jim|joe).*")); s = "humbapumpa jom"; assertFalse(s.matches(".*(jim|joe).*")); s = "humbaPumpa joe"; assertTrue(s.matches(".*(jim|joe).*")); s = "humbapumpa joe jim"; assertTrue(s.matches(".*(jim|joe).*")); } } 6.2. 匹配电话号码 任务: 编写正则表达式, 匹配各种电话号码。 假设电话号码(Phone number)的格式为 “7位连续的数字”; 或者是 “3位数字加空格/横线, 再加上4位数字”。 package de.vogella.regex.phonenumber; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class CheckPhone { @Test public void testSimpleTrue() { String pattern = "\\d\\d\\d([,\\s])?\\d\\d\\d\\d"; String s= "1233323322"; assertFalse(s.matches(pattern)); s = "1233323"; assertTrue(s.matches(pattern)); s = "123 3323"; assertTrue(s.matches(pattern)); } } 6.3. 判断特定数字范围 以下示例用来判断文本中是否具有连续的3位数字。 创建 de.vogella.regex.numbermatch 包和下面的类。 package de.vogella.regex.numbermatch; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class CheckNumber { @Test public void testSimpleTrue() { String s= "1233"; assertTrue(test(s)); s= "0"; assertFalse(test(s)); s = "29 Kasdkf 2300 Kdsdf"; assertTrue(test(s)); s = "99900234"; assertTrue(test(s)); } public static boolean test (String s){ Pattern pattern = Pattern.compile("\\d{3}"); Matcher matcher = pattern.matcher(s); if (matcher.find()){ return true; } return false; } } 6.4. 校验超链接 假设需要从网页中找出所有的有效链接。当然,需要排除 “javascript:” 和 “mailto:” 开头的情况。 创建 de.vogella.regex.weblinks 包, 以及下面的类: package de.vogella.regex.weblinks; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LinkGetter { private Pattern htmltag; private Pattern link; public LinkGetter() { htmltag = Pattern.compile("<a\\b[^>]*href=\"[^>]*>(.*?)</a>"); link = Pattern.compile("href=\"[^>]*\">"); } public List<String> getLinks(String url) { List<String> links = new ArrayList<String>(); try { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new URL(url).openStream())); String s; StringBuilder builder = new StringBuilder(); while ((s = bufferedReader.readLine()) != null) { builder.append(s); } Matcher tagmatch = htmltag.matcher(builder.toString()); while (tagmatch.find()) { Matcher matcher = link.matcher(tagmatch.group()); matcher.find(); String link = matcher.group().replaceFirst("href=\"", "") .replaceFirst("\">", "") .replaceFirst("\"[\\s]?target=\"[a-zA-Z_0-9]*", ""); if (valid(link)) { links.add(makeAbsolute(url, link)); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return links; } private boolean valid(String s) { if (s.matches("javascript:.*|mailto:.*")) { return false; } return true; } private String makeAbsolute(String url, String link) { if (link.matches("http://.*")) { return link; } if (link.matches("/.*") && url.matches(".*$[^/]")) { return url + "/" + link; } if (link.matches("[^/].*") && url.matches(".*[^/]")) { return url + "/" + link; } if (link.matches("/.*") && url.matches(".*[/]")) { return url + link; } if (link.matches("/.*") && url.matches(".*[^/]")) { return url + link; } throw new RuntimeException("Cannot make the link absolute. Url: " + url + " Link " + link); } } 6.5. 查找重复的单词 下面的正则表达式用来匹配重复的单词。 \b(\w+)\s+\1\b \b 是单词边界, \1 则引用第一个分组, 此处的第一个分组为前一个单词 (\w+)。 (?!-in)\b(\w+) \1\b 通过环视否定, 来匹配前面不是 “-in” 开始的重复单词。 提示: 可以在最前面加上 (?s) 标志来执行跨行搜索。 6.6. 查找每行起始位置的元素 下面的正则, 用来查找一行开头的单词 “title”, 前面允许有空格。 (\n\s*)title 6.7. 找到非Javadoc风格的语句 有时候, 在Java代码中会出现非Javadoc风格(Non-Javadoc)的语句; 如 Java 1.6 中的 @Override 注解, 用于告诉IDE该方法覆写了超类方法。这种是可以从源码中清除的。下面的正则用来找出这类注解。 (?s) /\* \(non-Javadoc\).*?\*/ 6.7.1. 用 Asciidoc 替换 DocBook 声明 例如有下面这样的XML: <programlisting language="java"> <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="./examples/statements/MyClass.java" /> </programlisting> 可以用下面的正则来匹配: `\s+<programlisting language="java">\R.\s+<xi:include xmlns:xi="http://www\.w3\.org/2001/XInclude" parse="text" href="\./examples/(.*).\s+/>\R.\s+</programlisting>` 替换目标可以是下面这样的regex: `\R[source,java]\R----\R include::res/$1[]\R---- 7. 在Eclipse中使用正则表达式 在Eclipse或者其他编辑器中, 可以使用正则来执行查找和替换。一般使用快捷键 Ctrl+H 打开 搜索/Search 对话框。 选择 File Search 选项卡, 并勾选 Regular expression 标识, 则可以进行正则查找/替换。当然, 还可以指定文件类型, 以及查找/替换的目录范围。 下图展示了如何查找XML标签 <![CDATA[]]]> 和前面的空格, 以及如何去除这些空格。 在结果对话框中可以查看有哪些地方会被替换, 可以去掉不想替换的元素。没问题的话, 点击 OK 按钮, 就会进行替换。 8. 相关链接 示例代码下载: http://www.vogella.com/code/index.html Regular-Expressions.info on Using Regular Expressions in Java Regulare xpressions examples The Java Tutorials: Lesson: Regular Expressions 原文链接: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html 原文日期: 2016.06.24 翻译日期: 2017-12-28 翻译人员: 铁锚 http://blog.csdn.net/renfufei/

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

Q#语言入门1 操作operation

Q# 程序会包含一个或多个操作(operation)。操作描述了量子操作带来的影响。 还可以包含一个或多个方法(function)。方法用来操作经典数据,只用来计算。 每个操作还可以调用其他操作(这不就是java里的方法吗?说对了一半,是java里的静态方法)。 Q#文件被编译后,每个操作都会是一个.net的类。所以Q#的操作可以被.net的其他语言调用。 一个操作会有一个输入、一个输出,会有一个body体。 下面定义一个操作: operation BitFlip(target : Qubit) : () { body { X(target); } } 它的输出是一个空的元组,类似与void,或者F#里的unit。

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

jsp自定义标记入门

JSP自定义标记为在动态 Web 页中将页面表示与业务逻辑分离提供了一种标准化的机制,使页面设计者可以将注意力放到页面表示上,而应用程序开发人员则专注于编写后端的代码。您可能听说现在有上百种不同的方式,但是在开发 Web 应用程序时将表示逻辑与业务逻辑分离是很重要的。近年来,Java 平台已经发展为在体系结构层次上加入了这种分离。例如,在 JSP 体系结构中加入 JavaBean 组件使开发人员使用 JSP 标记获得和设置经过特别编码的 java 组件上的属性。这些组件或者 JavaBean 再代表表示层执行后端业务处理。 JSP 自定义标记是 JSP/JavaBean 体系结构的产物。像 JavaBean 技术一样,自定义标记有助于将表示逻辑与业务逻辑分离。并且自定义标记成了 Web 设计者的 HTML、XML 和 Javascript 世界与软件工程师的 Java 代码、SQL 调用和算法世界之间的桥梁。 JSP 自定义标记 JSP 自定义标记 是用户定义的标记,它遵循 JSP JavaBean 标记(即 useBean、getProperty 和 setProperty)所使用的一种特殊的 xml 语法。当 servlet 容器处理自定义标记时,会调用一个或者多个 Java 类文件处理它,与用 Java 类文件处理 JSP 页面的 JavaBean 调用的方式基本一样。处理标记以后,容器将取其名字和属性、以及标记正文中可能有的任何内容,并将它传递给一个或者多个类文件进行处理。 Java 开发人员编写标记处理程序类以处理标记并处理所有需要的 Java 代码和数据操作。对于 Web 设计者来说,自定义标记与标准 html 标记除了都可以利用后端动态数据外,它们看上去与使用起来没什么区别。正确编写自定义标记可以让 Web 设计者创建、查询和操作数据而无需编写一行 Java 代码。正确使用自定义标记使 Java 开发人员不必再在编码过程中考虑表示层。这样应用程序开发小组的每一位成员都可以关注于他或者她最擅长的事物。 实现 JSP 自定义标记 JSP 体系结构需要以下组件以实现自定义标记: 在每一页中有一个 JSP 声明 Web 应用程序描述符(web.xml)中的一个项 一个包含特殊 XML 文件和为处理自定义标记而调用的 Java 类的 JAR 文件 要想成功实现 JSP 自定义标记,您需要采取下面四个步骤: 编写标记处理程序类。 创建标记库描述符(TLD)。 引用标记库。 在 JSP 页面中使用标记。 那我们就以经典的"Hello,World"开始吧。。。 第 1 步. 编写标记处理程序类 我们要做的第一件事是编写标记处理程序类。在执行引用自定义标记的 JSP 页面时,JSP 容器判断每一个自定义标记。当容器遇到一个标记时,它调用与这个自定义标记相关联的标记处理程序,我们将在后面更多地讨论这个过程。然后,每一个标记处理程序实现 JSP API中的一个特殊接口。标记有两种类型:可以处理标记内容(或者正文)的标记和不能处理标记内容的标记: <abc:tagWithNoBody attribute="value"/> <abc:tagWithBody attribute="value"> This is some body content that the tag handler can operate upon. </abc:tagWithBody> 在 例子中不需要加入正文内容,因为它只显示一个字符串。因此,我们的处理程序类将实现 Tag 接口(一般是通过扩展 TagSupport 类)。如果我们要创建一个可以处理正文的标记,那么我们就需要实现 BodyTag 接口(一般是通过扩展 BodyTagSupport 类)。 清单 1. 标记处理程序类 package com.vitamin.taglib; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag implements Tag { private PageContext context = null;//页面上下文 public HelloTag() { super(); // TODO 自动生成构造函数存根 } public void setPageContext(PageContext pageContext) { this.context = pageContext; } public void setParent(Tag tag) { } public Tag getParent() { return null; } public int doStartTag()throws JspException { try { this.context.getOut().println("hello,world"); } catch(IOException ex) { throw new JspException(ex.getMessage()); } return Tag.SKIP_BODY; } public int doEndTag() { return Tag.SKIP_PAGE; } public void release() { } } 当然在这里值得注意的是,我这是采用了实现Tag接口的方法来做的,其实更好的方式是继承自TagSupport类。因为 TagSupport 类是简单的、具体类,它完全实现了在 Tag 接口中声明的方法,我们可以只实现那些在自定义标记中要使用的方法。 第 2 步. 创建 TLD 下一步是定义包含自定义标记与处理它的 Java 类(或多个类)之间的映射的库。这个库是在一个名为标记库描述符(TLD)的 XML 文档中定义的。 清单 2. mytag.tld 文件 <?xml version="1.0" encoding="UTF-8"?> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>hello</shortname> <tag> <name>sayHello</name> <tagclass>com.vitamin.taglib.HelloTag</tagclass> <bodycontent>empty</bodycontent> </tag> </taglib> 所有关键信息都包含在 Tag 标记中,在这里映射了标记名和处理程序类,我们声明了标记对于正文内容的敏感性。对于更复杂的情况,我们可以使用其他的 XML 标记以提供有关库和标记的更多信息。在一个库中定义多个标记也很常见。 第 3 步. 引用这个标记库 有两种方法声明 JSP 页面与其库之间的引用。可以通过 Web 应用程序描述符(web.xml)声明一个静态引用,也可以直接在页面中声明一个动态引用。(可奇怪的是,我在用静态引用时,居然失败,web.xml里面放进去声明时就会报错。。。) 为了进行动态引用,只需在所有需要使用这个库的页面中加入一个 JSP 声明即可: <%@ taglib uri="/WEB-INF/mytag.tld" prefix="hello" %> 静态引用与动态引用的比较 在进行标记库的静态引用时,JSP 声明必须查询 web.xml 文件以执行库查询。这意味着如果移动或者重命名了库,或者希望在 web.xml 文件中加入更多的库,就必须停止服务器、更新 web.xml 文件、然后重新启动服务器。动态方法让 JSP 页直接指向 TLD 位置,因而是在解释 JSP 页面时进行处理。 静态方法提供了页面与库的实际名和位置之间一定程度的非直接性,这可以为您提供一些改变这些属性而不修改页面的灵活性。另一方面,动态方法提供了更大的灵活性,让您可以在运行时增加和移动标记声明。如果您对动态方法感兴趣,但是又担心做了一些改变后、有可能要更新多个页面的维护负担,那么您可以始终将 JSP 声明放到一个单独的 JSP 文件中,并在每一个要访问 Web 应用程序的自定义库的页面中加入这一页。这使您具有在运行时只需要更新信息一次就可以增加库的灵活性。 第 4 步. 在 JSP 页面中使用标记 完成了所有这些准备工作后,我们就可以在 JSP 页面中使用这些自定义标记了。 清单 3. 带有自定义标记的 JSP 页 <%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <%@ taglib uri="/WEB-INF/mytag.tld" prefix="hello" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <hello:sayHello/> </body> </html> 用JSTL 节省时间 您所需要的自定义标记功能中也许有多达百分之八十已经由 J2EE 团体创建并标准化了。使用现有的标记库而不是从头创建所有东西会使您节省大量时间和精力。尽管在公共域有数十种库,不过业界汇集了一个特定的自定义库。Java 标准标记库(JSTL)是由 Java Community Process 设计的,其参考实现是由 Apache Group 通过 Jakarta Taglibs 项目所开发和维护的. JSTL 定义了针对常见 Web 应用程序处理需求,如变量支持、流程控制、URL 管理、XML 操作、国际化、数据库访问等等的标记。除了一组丰富的标记外,JSTL 还定义了自己的表达式语言(EL)。EL 使我们可以容易地访问应用程序数据并更容易在不使用脚本或者请求时表达式的条件下操作这些数据。 除了节省您从头开发所有标记的时间和精力,JSTL 还具有标准化和业界承认的所有好处。这些好处包括厂商支持、大量介绍文字、以及有很大的机会找到具有 JSTL 经验的雇员或者承包商。 结束语 在 J2EE Web 开发中越来越多地需要将业务和表示逻辑分离,JSP 自定义标记提供了替代简单的老 JavaBean 和 Java 脚本的一个有吸引力的方法。更好的是在 JSTL 中已存在一组已定义的标准的自定义标记库。 另外,标记库技术虽然解决了java代码和html混合的问题,但却带来了另一个问题,就是使用了标记库的页面不能进行可视化设计了!!!因为开发工具根本不能运行你后台的代码,所以就显示不出来页面的结果了。于是,JSF就出现了。它一改以往的基于Web的Request-Response处理机制,而是采用了类似Swing的的事件驱动处理机制。它简化了Web表单的有效性验证,Request参数解析,状态管理和多线程支持等任务,我们只需要实现具体的事件处理模块和事件逻辑模块就可以了。 本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2006/06/25/435236.html,如需转载请自行联系原作者

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

swift:入门知识之协议与扩展

swift中使用protocol声明一个协议接口 swift中类、枚举和结构体都可以实现协议接口 swift中类中的方法都可以修改成员变量的值 swift中结构体中的方法默认是不能修改成员变量的,添加mutating关键字后就可以修改了 swift中使用extension来为现有的类型添加功能。你可以使用扩展来给任意类型添加协议,甚至是你从外部库或者框架中导入的类型 swift中协议接口的委托代理模式和Objective-C基本上是一样的,都是主方设置一个代理人,然后将事情的处理委托给这个代理人去办,而主方自己只需要声明协议的规则即可。记住,代理人必须按照主方设定的规则去处理这些需要做的事情。不管代理人是谁,只要遵从协议就可以成为主方的委托者。 Swift 中的扩展可以: 1. 添加计算型属性和计算静态属性 2. 定义实例方法和类型方法 3. 提供新的构造器 4. 定义下标 5. 定义和使用新的嵌套类型 6. 使一个已有类型符合某个接口 具体举例如下: //声明一个ExampleProtocol协议,有一个成员变量和一个默认必须实现的方法 //声明一个协议 protocol ExampleProtocol{ //声明一个成员变量,并设置一个getter方法 var simpleDescription:String{get} mutating func adjust() } //定义一个SimpleClass类继承ExampleProtocol协议 //定义一个类继承协议 class SimpleClass: ExampleProtocol { var simpleDescription:String = "A very simple class" func adjust() { simpleDescription += " adjust" } } var simpleclass = SimpleClass() //创建对象 simpleclass.adjust() //实现下一中的必须实现的方法 simpleclass.simpleDescription //用get方法获取属性值 "A very simple class adjust" //定义一个SimpleStruct结构体继承ExampleProtocol协议 //定义一个结构体继承协议 struct SimpleStruct:ExampleProtocol { var simpleDescription:String = "A very simple struct" //必须用关键词mutating修饰,才能修改属性值 mutating func adjust() { simpleDescription += "struct" } } var simplestruct = SimpleStruct() //创建结构体成员变量 simplestruct.adjust() //实现下一中的必须实现的方法 simplestruct.simpleDescription //用get方法获取属性值 "A very simple structstruct --------------------------------------------------------------------------------------------------------- //声明一个Myprotocol协议,有一个成员变量和一个默认必须实现的方法,还有一个可选的方法 //定义一个有可选方法的协议 @objc protocol MyProtocol{ //声明一个成员变量,并设置一个getter和setter方法 var contentDescription:String {get set} func method() //可选的方法 optional func adjust() } //定义一个Boy类继承Myprotocol这个协议 class Boy:MyProtocol{ var contentDescription:String = "he is a boy" //实现可选的方法 func method() { contentDescription += ",good dood study" } //实现必须实现的方法 func adjust(){ contentDescription += ",okay" } } let boy = Boy() boy.contentDescription = "Tom" //set方法赋值 boy.method() //实现必须实现的方法 boy.adjust() //实现可选的方法 boy.contentDescription //get方法取值 "Tom ,good good study,okay" --------------------------------------------------------------------------------------------------------- //定义一个扩展继承ExampleProtocol协议 //定义一个类扩展 extension Int:ExampleProtocol{ var simpleDescription:String{ return "The number \(self)" } mutating func adjust(){ self += 24 } } 7.simpleDescription // 7 //自定义一个扩展 程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式! 分类: Swift开发技术 本文转自当天真遇到现实博客园博客,原文链接: http://www.cnblogs.com/XYQ-208910/p/4905128.html如需转载请自行联系原作者

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

Docker 从入门到放弃(一)安装

前言 Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux机器上,也可以实现虚拟化,容器是完全使用沙箱机制,相互之间不会有任何接口。 Docker采用 C/S架构 Docker daemon 作为服务端接受来自客户的请求,并处理这些请求(创建、运行、分发容器)。 客户端和服务端既可以运行在一个机器上,也可通过 socket 或者RESTful API 来进行通信。 Docker daemon 一般在宿主主机后台运行,等待接收来自客户端的消息。 Docker 客户端则为用户提供一系列可执行命令,用户用这些命令实现跟 Docker daemon 交互。 安装 前提条件 Docker 要求 Ubuntu 系统的内核版本高于 3.10 ,查看本页面的前提条件来验证你的 Ubuntu 版本是否支持 Docker。 通过 uname -r 命令查看你当前的内核版本 # uname -r 4.4.0-93-generic 使用脚本安装 Docker 1、获取最新版本的 Docker 安装包 # wget -qO- https://get.docker.com/ | sh # Executing docker install script, commit: 11aa13e + sh -c apt-get update -qq >/dev/null + sh -c apt-get install -y -qq apt-transport-https ca-certificates curl software-properties-common >/dev/null + sh -c curl -fsSL "https://download.docker.com/linux/ubuntu/gpg" | apt-key add -qq - >/dev/null + sh -c echo "deb [arch=amd64] https://download.docker.com/linux/ubuntu trusty edge" > /etc/apt/sources.list.d/docker.list + [ ubuntu = debian ] + sh -c apt-get update -qq >/dev/null + sh -c apt-get install -y -qq --no-install-recommends docker-ce >/dev/null + sh -c docker version Client: Version: 17.11.0-ce API version: 1.34 Go version: go1.8.3 Git commit: 1caf76c Built: Mon Nov 20 18:36:37 2017 OS/Arch: linux/amd64 Server: Version: 17.11.0-ce API version: 1.34 (minimum version 1.12) Go version: go1.8.3 Git commit: 1caf76c Built: Mon Nov 20 18:35:10 2017 OS/Arch: linux/amd64 Experimental: false If you would like to use Docker as a non-root user, you should now consider adding your user to the "docker" group with something like: sudo usermod -aG docker your-user Remember that you will have to log out and back in for this to take effect! WARNING: Adding a user to the "docker" group will grant the ability to run containers which can be used to obtain root privileges on the docker host. Refer to https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface for more information. 安装完成后有个提示: 当要以非root用户可以直接运行docker时,需要执行 sudo usermod -aG docker runoob 命令,然后重新登陆,否则会报错 2、启动docker 后台服务 sudo service docker start start: Job is already running: docker 3、用Hello World校验Docker的安装 用Docker运行Hello World镜像,命令如下: # docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world ca4f61b1923c: Pull complete Digest: sha256:be0cd392e45be79ffeffa6b05338b98ebb16c87b255f48e297ec7f98e123905c Status: Downloaded newer image for hello-world:latest Hello from Docker! This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (amd64) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash Share images, automate workflows, and more with a free Docker ID: https://cloud.docker.com/ For more examples and ideas, visit: https://docs.docker.com/engine/userguide/ 可见,Docker注册服务器从Docker Hub获取到最新的Hello World镜像,下载到了本地。可以再次运行Hello World镜像。 # docker run hello-world Hello from Docker! This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (amd64) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash Share images, automate workflows, and more with a free Docker ID: https://cloud.docker.com/ For more examples and ideas, visit: https://docs.docker.com/engine/userguide/ 二、使用 1、Docker Hello World Docker 允许你在容器内运行应用程序, 使用 docker run 命令来在容器内运行一个应用程序 root@aliyunTinywan:~# docker run ubuntu:15.10 /bin/echo "Hello world" Unable to find image 'ubuntu:15.10' locally 15.10: Pulling from library/ubuntu 7dcf5a444392: Pull complete 759aa75f3cee: Pull complete 3fa871dc8a2b: Pull complete 224c42ae46e7: Pull complete Digest: sha256:02521a2d079595241c6793b2044f02eecf294034f31d6e235ac4b2b54ffc41f3 Status: Downloaded newer image for ubuntu:15.10 Hello world Docker首先从本地主机上查找镜像是否存在,如果不存在,Docker 就会从镜像仓库 Docker Hub 下载公共镜像。这里发现镜像ubuntu:15.10 不存在,正在从镜像仓库下载 参数解析: docker:Docker 的二进制执行文件。 run:与前面的 docker 组合来运行一个容器。 ubuntu:15.10:指定要运行的镜像,Docker首先从本地主机上查找镜像是否存在,如果不存在,Docker 就会从镜像仓库Docker Hub下载公共镜像。 /bin/echo "Hello world":在启动的容器里执行的命令 root@aliyunTinywan:~# docker run ubuntu:15.10 /bin/echo "Hello world" Hello world 以上命令完整的意思可以解释为:Docker 以 ubuntu15.10 镜像创建一个新容器,然后在容器里执行 bin/echo "Hello world",然后输出结果。 2、运行交互式的容器 通过docker的两个参数 -i -t,让docker运行的容器实现"对话"的能力 root@aliyunTinywan:~# docker run -i -t ubuntu:15.10 /bin/bash root@aliyunTinywan:/# 参数解析: -t:在新容器内指定一个伪终端或终端。 -i:允许你对容器内的标准输入 (STDIN) 进行交互。 此时我们已进入一个 ubuntu15.10系统的容器,尝试在容器中运行命令 cat /proc/version 和 ls 分别查看当前系统的版本信息和当前目录下的文件列表 root@aliyunTinywan:/# cat /proc/version Linux version 4.4.0-93-generic (buildd@lcy01-28) (gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3) ) #116~14.04.1-Ubuntu SMP Mon Aug 14 16:07:05 UTC 2017 root@aliyunTinywan:/# cat /etc/issue Ubuntu 15.10 \n \l root@aliyunTinywan:/# ls bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var 可以通过运行exit命令或者使用CTRL+D来退出容器,查看当前真实的服务器系统版本 root@18c5f2d5476b:/# exit exit root@iZ235mi4a64Z:~# cat /etc/issue Ubuntu 14.04.5 LTS \n \l 3、启动容器(后台模式) 使用以下命令创建一个以进程方式运行的容器 root@iZ235mi4a64Z:~# docker run -d ubuntu:15.10 /bin/sh -c "while true; do echo hello world; sleep 1; done" 6ddd469230b5402251c4fd3214b63f6a6af7d9e2711f8944a9d74b36346bbd5a 在输出中,我们没有看到期望的"hello world",而是一串长字符 2b1b7a428627c51ab8810d541d759f072b4fc75487eed05812646b8534a2fe63 这个长字符串叫做容器ID,对每个容器来说都是唯一的,我们可以通过容器ID来查看对应的容器发生了什么。 首先,我们需要确认容器有在运行,可以通过 docker ps 来查看 root@iZ235mi4a64Z:~# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 6ddd469230b5 ubuntu:15.10 "/bin/sh -c 'while t…" About a minute ago Up About a minute romantic_visvesvaraya CONTAINER ID:容器ID NAMES:自动分配的容器名称 在容器内使用docker logs命令,查看容器内的标准输出 (1)使用ID root@iZ235mi4a64Z:~# docker logs 6ddd469230b5 hello world hello world hello world ... (2)使用NAMES root@iZ235mi4a64Z:~# docker logs romantic_visvesvaraya hello world hello world ... 发现结果是一样的,输出了同样的结果 4、停止容器 使用 docker stop 命令来停止容器,让然啦,要指定停止的容器对象啦,不然会这样子 root@iZ235mi4a64Z:~# docker stop "docker stop" requires at least 1 argument. See 'docker stop --help'. Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...] [flags] Stop one or more running containers 指定一个容器 root@iZ235mi4a64Z:~# docker stop 6ddd469230b5 6ddd469230b5 通过 docker ps 查看,容器已经停止工作 root@iZ235mi4a64Z:~# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 也可以用下面的NAMES命令来停止 docker stop romantic_visvesvaraya

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

Docker入门实战-SSH连接docker容器

简介 什么是Docker Docker 是一个开源项目,诞生于 2013 年初,最初是 dotCloud 公司内部的一个业余项目。它基于 Google 公司推出的 Go 语言实现。 项目后来加入了 Linux 基金会,遵从了 Apache 2.0 协议,项目代码在 GitHub 上进行维护。 Docker 自开源后受到广泛的关注和讨论,以至于 dotCloud 公司后来都改名为 Docker Inc。Redhat 已经在其 RHEL6.5 中集中支持 Docker;Google 也在其 PaaS 产品中广泛应用。 Docker 项目的目标是实现轻量级的操作系统虚拟化解决方案。 Docker 的基础是 Linux 容器(LXC)等技术。 在 LXC 的基础上 Docker 进行了进一步的封装,让用户不需要去关心容器的管理,使得操作更为简便。用户操作 Docker 的容器就像操作一个快速轻量级的虚拟机一样简单。 下面的图片比较了 Docker 和传统虚拟化方式的不同之处,可见容器是在操作系统层面上实现虚拟化,直接复用本地主机的操作系统,而传统方式则是在硬件层面实现。 为什么要用Docker 作为一种新兴的虚拟化方式,Docker 跟传统的虚拟化方式相比具有众多的优势。 首先,Docker 容器的启动可以在秒级实现,这相比传统的虚拟机方式要快得多。 其次,Docker 对系统资源的利用率很高,一台主机上可以同时运行数千个 Docker 容器。 容器除了运行其中应用外,基本不消耗额外的系统资源,使得应用的性能很高,同时系统的开销尽量小。传统虚拟机方式运行 10 个不同的应用就要起 10 个虚拟机,而Docker 只需要启动 10 个隔离的应用即可。 具体说来,Docker 在如下几个方面具有较大的优势。 更快速的交付和部署 对开发和运维(devop)人员来说,最希望的就是一次创建或配置,可以在任意地方正常运行。 开发者可以使用一个标准的镜像来构建一套开发容器,开发完成之后,运维人员可以直接使用这个容器来部署代码。 Docker 可以快速创建容器,快速迭代应用程序,并让整个过程全程可见,使团队中的其他成员更容易理解应用程序是如何创建和工作的。 Docker 容器很轻很快!容器的启动时间是秒级的,大量地节约开发、测试、部署的时间。 更高效的虚拟化 Docker 容器的运行不需要额外的 hypervisor 支持,它是内核级的虚拟化,因此可以实现更高的性能和效率。 更轻松的迁移和扩展 Docker 容器几乎可以在任意的平台上运行,包括物理机、虚拟机、公有云、私有云、个人电脑、服务器等。 这种兼容性可以让用户把一个应用程序从一个平台直接迁移到另外一个。 更简单的管理 使用 Docker,只需要小小的修改,就可以替代以往大量的更新工作。所有的修改都以增量的方式被分发和更新,从而实现自动化并且高效的管理。 对比传统虚拟机总结 特性 容器 虚拟机 启动 秒级 分钟即 硬盘使用 一般为MB 一般为GB 性能 接近原生 弱于 系统支持量 单机支持上千个容器 一般几十个 安装Docker 本来打算在CentOS6上安装Docker,最终由于CentOS6上自带的kernel版本太低导致Docker启动失败而放弃(kernel升级太繁琐)。 下面使用CentOS7安装Docker,本人采用虚拟机的方式来安装,安装好的虚拟机必须保证能访问外网。 CentOS7 系统 CentOS-Extras 库中已带 Docker,可以直接安装: $ sudo yum install docker 安装之后启动 Docker 服务,并让它随系统启动自动加载: $ sudo service docker start $ sudo chkconfig docker on 获取镜像 可以使用 docker pull 命令来从仓库获取所需要的镜像。 下面的例子将从 Docker Hub 仓库下载一个Centos6并且安装了jdk7的镜像: $ docker pull tcbenkhard/centos6-jdk7 列出本地镜像 使用 docker images 显示本地已有的镜像。 $ docker images 启动容器 启动容器有两种方式,一种是基于镜像新建一个容器并启动,另外一个是将在终止状态(stopped)的容器重新启动。 因为 Docker 的容器实在太轻量级了,很多时候用户都是随时删除和新创建容器。 下面的命令则启动一个 bash 终端,允许用户进行交互。 $ docker run -t -i docker.io/tcbenkhard/centos6-jdk7 /bin/bash [root@ffe81683c404 /]# 其中,-t 选项让Docker分配一个伪终端(pseudo-tty)并绑定到容器的标准输入上,-i 则让容器的标准输入保持打开。 当利用 docker run 来创建容器时,Docker 在后台运行的标准操作包括: (1)检查本地是否存在指定的镜像,不存在就从公有仓库下载 (2)利用镜像创建并启动一个容器 (3)分配一个文件系统,并在只读的镜像层外面挂载一层可读写层 (4)从宿主主机配置的网桥接口中桥接一个虚拟接口到容器中去 (5)从地址池配置一个 ip 地址给容器 (6)执行用户指定的应用程序 (7)执行完毕后容器被终止 可以使用下面命令来查看CentOS版本信息: $ cat /etc/redhat-release 修改root密码 使用passwd密码来修改密码(如提示没有这个命令行使用yum install passwd安装): $ passwd xxx密码 xxx确认密码123 安装Openssh 使用下面命令安装ssh server/ssh client: $ sudo yum -y install openssh-server $ sudo yum -y install openssh-clients 修改SSH配置文件以下选项,去掉#注释,将四个选项启用: $ vi /etc/ssh/sshd_config RSAAuthentication yes #启用 RSA 认证 PubkeyAuthentication yes #启用公钥私钥配对认证方式 AuthorizedKeysFile .ssh/authorized_keys #公钥文件路径(和上面生成的文件同) PermitRootLogin yes #root能使用ssh登录123456 重启ssh服务,并设置开机启动: $ service sshd restart $ chkconfig sshd on 退出容器并保存更改 使用exit命令或者ctrl+C来退出当前运行的容器: [root@ffe81683c404 /]# exit 注意:上面ffe81683c404是容器的ID,退出后用于保存的唯一ID。 当结束后,我们使用 exit 来退出,现在我们的容器已经被我们改变了,使用 docker commit 命令来提交更新后的副本。 $ sudo docker commit -m 'install openssh' -a 'Docker Newbee' ffe81683c404 centos6-jdk7:ssh 4f177bd27a9ff0f6dc2a830403925b5360bfe0b93d476f7fc3231110e7f71b1c12 其中,-m 来指定提交的说明信息,跟我们使用的版本控制工具一样;-a 可以指定更新的用户信息;之后是用来创建镜像的容器的ID;最后指定目标镜像的仓库名和 tag 信息。创建成功后会返回这个镜像的 ID 信息。 提交后docker中就会多出一个centos6-jdk7:ssh的一个镜像。 启动新的容器并打通22端口 将新的镜像启动,并将docker服务器的50001端口映射到容器的22端口上: $ docker run -d -p 50001:22 centos6-jdk7:ssh /usr/sbin/sshd -D ssh连接容器: 至此SSH连接docker容器成功完成。 本文转自 dengaosky 51CTO博客,原文链接:http://blog.51cto.com/dengaosky/1854114,如需转载请自行联系原作者

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

存储新手入门参考资料

存储相关资料 为了便于自己和大家学习,整理了网上可以查到的存储领域相关书籍、博客、论坛和网站,和大家一起分享,欢迎一起完善。 书籍类 大话存储 现代存储发展的主流技术史,重点介绍了RAID/FiberChannel/SAN. 大话存储2 主要目录结构和大话存储1差不多,加入了最新的云存储相关章节,内容全面,视野开阔,特别是增添了很多具体的技术讲解、对比和总结,是从业人员快速打基础的好书。 下载链接:http://download.csdn.net/download/yunxin170/3665772 西安电子科技大学:存储基础知识 书如其名,虽然离新技术和潮流有些距离,但是基础知识讲得很全,特别适合做教材。 存储技术原理分析:基于Linux2.6内核原代码 一本从内核角度学习SCIS/IO/RAID/Multi-Disk的原理分析书籍,适合Driver开发和性能分析参考。 网络存储与数据备份 随着数据量的增长,数据从GB级到TB级转变,需要的存储空间越来越大,对存储设备要求越来越高,存储技术的更新对存储空间的增加提供了多种模式的数据安全保证,存储设备已经成为网络中不可或缺的基础组件,成为网络设备的“必选件”。备份是保证数据安全的重要手段之一,虽然存储设备中安全技术的增强己经起到了保护数据安全的作用,但是备份依然是数据安全的首选模式。本书从存储和备份两个层次入手,介绍在网络中最常用到的存储技术和备份手段。 本书语言流畅、通俗易懂、深入浅出、可操作性强,注重读者实战能力的培养和技术水平的提高。本书适用于网络管理人员,以及对网络感兴趣的计算机爱好者,并可作为大专院校计算机专业的教材或课后辅导资料。 华中科技大学出版社:海量网络存储系统原理 不愧是院校专家出品,该书从理论和实践两个方面,全面系统地对海量网络存储系统各个方面的问题进行深入分析和讨论,并结合自身的科研成果以实例的方式细致描述存储系统的研究手段、实现方式和整体思路。 成就存储专家之路 偏上层的应用及架构介绍,适合数据中心管理员、咨询师和架构师参考 个人推荐 对开发人员:大话2和存储技术原理分析; 对研究人员:海量网络存储系统原理 技术链接和论坛 EMC:https://community.emc.com/community/support/chinese/storagehw Lenovo: http://wenku.baidu.com/link?url=bsayl0W4RxUbIM1jQMLO_8AyRFg_DmBaoYHVZdHOG6NoWiIIyckA9Py96HgvmLMsACAGkIA6u52kw19TDNUbKWIKLqBqrxMDE4bFHpLmjOS 行业动态 置顶网:http://stor-age.zdnet.com.cn/stor-age/ 比特网:http://storage.chinabyte.com/ 硅谷动力:http://www.enet.com.cn/storage/ 存储经理人:http://www.searchstorage.com.cn/ 赛迪网存储:http://www.ccidnet.com/product/storage/ 相关会议 中国存储峰会:http://doitworld.doit.com.cn/ 存储开发者会议:http://www.snia.org/events/storage-developer 文件和存储系统:https://www.usenix.org/legacy/events/fast08/ 学术相关: http://www.usenix.org/events/ http://iweb.tntech.edu/hexb/ http://www.usenix.org/event/ 博客 冬瓜头的博客http://melonhead.blog.51cto.com/ 存储之道的博客 http://alanwu.blog.51cto.com/ 范军的博客:http://frankfan.blog.51cto.com/ 大数据在线:http://yuanshaolong.blog.51cto.com/ 本文转自存储之厨51CTO博客,原文链接:http://blog.51cto.com/xiamachao/1681020,如需转载请自行联系原作者

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

python spark 决策树 入门demo

Refer to theDecisionTreePython docsandDecisionTreeModelPython docsfor more details on the API. from pyspark.mllib.tree import DecisionTree, DecisionTreeModel from pyspark.mllib.util import MLUtils # Load and parse the data file into an RDD of LabeledPoint. data = MLUtils.loadLibSVMFile(sc, 'data/mllib/sample_libsvm_data.txt') # Split the data into training and test sets (30% held out for testing) (trainingData, testData) = data.randomSplit([0.7, 0.3]) # Train a DecisionTree model. # Empty categoricalFeaturesInfo indicates all features are continuous. model = DecisionTree.trainClassifier(trainingData, numClasses=2, categoricalFeaturesInfo={}, impurity='gini', maxDepth=5, maxBins=32) # Evaluate model on test instances and compute test error predictions = model.predict(testData.map(lambda x: x.features)) labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions) testErr = labelsAndPredictions.filter(lambda (v, p): v != p).count() / float(testData.count()) print('Test Error = ' + str(testErr)) print('Learned classification tree model:') print(model.toDebugString()) # Save and load model model.save(sc, "target/tmp/myDecisionTreeClassificationModel") sameModel = DecisionTreeModel.load(sc, "target/tmp/myDecisionTreeClassificationModel") Find full example code at "examples/src/main/python/mllib/decision_tree_classification_example.py" in the Spark repo. classpyspark.mllib.tree.DecisionTree[source] Learning algorithm for a decision tree model for classification or regression. New in version 1.1.0. classmethodtrainClassifier( data, numClasses, categoricalFeaturesInfo, impurity='gini', maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0) [source] Train a decision tree model for classification. Parameters: data– Training data: RDD of LabeledPoint. Labels should take values {0, 1, ..., numClasses-1}. numClasses– Number of classes for classification. categoricalFeaturesInfo– Map storing arity of categorical features. An entry (n -> k) indicates that feature n is categorical with k categories indexed from 0: {0, 1, ..., k-1}. impurity– Criterion used for information gain calculation. Supported values: “gini” or “entropy”. (default: “gini”) maxDepth– Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1 means 1 internal node + 2 leaf nodes). (default: 5) maxBins– Number of bins used for finding splits at each node. (default: 32) minInstancesPerNode– Minimum number of instances required at child nodes to create the parent split. (default: 1) minInfoGain– Minimum info gain required to create a split. (default: 0.0) Returns: DecisionTreeModel. Example usage: >>> from numpy import array >>> from pyspark.mllib.regression import LabeledPoint >>> from pyspark.mllib.tree import DecisionTree >>> >>> data = [ ... LabeledPoint(0.0, [0.0]), ... LabeledPoint(1.0, [1.0]), ... LabeledPoint(1.0, [2.0]), ... LabeledPoint(1.0, [3.0]) ... ] >>> model = DecisionTree.trainClassifier(sc.parallelize(data), 2, {}) >>> print(model) DecisionTreeModel classifier of depth 1 with 3 nodes >>> print(model.toDebugString()) DecisionTreeModel classifier of depth 1 with 3 nodes If (feature 0 <= 0.0) Predict: 0.0 Else (feature 0 > 0.0) Predict: 1.0 >>> model.predict(array([1.0])) 1.0 >>> model.predict(array([0.0])) 0.0 >>> rdd = sc.parallelize([[1.0], [0.0]]) >>> model.predict(rdd).collect() [1.0, 0.0] 摘自:https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.tree.DecisionTree 本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/7150483.html ,如需转载请自行联系原作者

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

centos6 - elk基础入门搭建

1 2 3 4 5 6 7 [root@host-192-168-53-108~] #rm-rf/etc/yum.repos.d/* [root@host-192-168-53-108~] #wget-O/etc/yum.repos.d/CentOS-Base.repohttp://mirrors.aliyun.com/repo/Centos-6.repo [root@host-192-168-53-108~] #yumcleanall [root@host-192-168-53-108~] #yum-yinstalljava-1.8.0-openjdk* [root@host-192-168-53-108~] #wgethttps://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.5.0.rpm [root@host-192-168-53-108~] #rpm-ivhelasticsearch-5.5.0.rpm [root@host-192-168-53-108~] #chkconfig--addelasticsearch 1 2 [root@host-192-168-53-108~] #cat/etc/hosts 192.168.53.108elk1 1 2 3 4 5 6 7 8 9 [root@host-192-168-53-108~] #cat/etc/elasticsearch/elasticsearch.yml node.name:elk1 network.host:192.168.53.108 http.port:9200 bootstrap.memory_lock: false bootstrap.system_call_filter: false discovery.zen. ping .unicast.hosts:[elk1] http.cors.enabled: true http.cors.allow-origin: "*" 1 2 3 4 [root@host-192-168-53-108~] #cat/etc/elasticsearch/jvm.options|grep-v'^#'|grep-v^$ #修改 -Xms6g -Xmx6g 1 2 3 4 5 [root@host-192-168-53-108~] #vim/etc/security/limits.conf *softnofile1000000 *hardnofile1000000 *softnproc1000000 *hardnproc1000000 1 2 3 [root@host-192-168-53-108~] #cat/etc/security/limits.d/90-nproc.conf *softnproc100000 rootsoftnprocunlimited 1 2 3 4 5 6 [root@host-192-168-53-108~] #cd/usr/local/ [root@host-192-168-53-108 local ] #gitclonegit://github.com/mobz/elasticsearch-head.git [root@host-192-168-53-108 local ] #wgethttps://nodejs.org/dist/v8.2.0/node-v8.2.0-linux-x64.tar.gz--no-check-certificate [root@host-192-168-53-108 local ] #tarzxfnode-v8.2.0-linux-x64.tar.gz [root@host-192-168-53-108 local ] #ln-s/usr/local/node-v8.2.0-linux-x64/bin/node/usr/sbin/node [root@host-192-168-53-108 local ] #ln-s/usr/local/node-v8.2.0-linux-x64/bin/npm/usr/sbin/npm 1 2 3 4 5 #设置npm代理镜像 [root@host-192-168-53-108 local ] #npmconfigsetregistryhttps://registry.npm.taobao.org [root@host-192-168-53-108 local ] #npminstall-ggrunt [root@host-192-168-53-108 local ] #ln-s/usr/local/node-v8.2.0-linux-x64/lib/node_modules/grunt/bin/grunt/usr/sbin/grunt [root@host-192-168-53-108 local ] #cdelasticsearch-head/ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 [root@host-192-168-53-108elasticsearch- head ] #npminstall Errormakingrequest. Error:connectETIMEDOUT52.216.1.0:443 atObject.exports._errnoException(util.js:1024:11) atexports._exceptionWithHostPort(util.js:1047:20) atTCPConnectWrap.afterConnect[asoncomplete](net.js:1150:14) Pleasereportthisfulllogathttps: //github .com /Medium/phantomjs npmWARNelasticsearch- head @0.0.0licenseshouldbeavalidSPDXlicenseexpression npmWARNoptionalSKIPPINGOPTIONALDEPENDENCY:fsevents@1.1.2(node_modules /fsevents ): npmWARNnotsupSKIPPINGOPTIONALDEPENDENCY:Unsupportedplatform for fsevents@1.1.2:wanted{ "os" : "darwin" , "arch" : "any" }(current:{ "os" : "linux" , "arch" : "x64" }) npmERR!codeELIFECYCLE npmERR!errno1 npmERR!phantomjs-prebuilt@2.1.14 install :`node install .js` npmERR!Exitstatus1 npmERR! npmERR!Failedatthephantomjs-prebuilt@2.1.14 install script. npmERR!Thisisprobablynotaproblemwithnpm.Thereislikelyadditionalloggingoutputabove. npmERR!Acompletelogofthisruncanbefound in : npmERR! /root/ .npm /_logs/2017-07-26T11_29_47_063Z-debug .log 1 2 [root@host-192-168-53-108elasticsearch- head ] #npminstallphantomjs-prebuilt@2.1.14--ignore-scripts [root@host-192-168-53-108elasticsearch- head ] #npminstall 1 2 3 4 [root@host-192-168-53-108elasticsearch- head ] #vim/usr/local/elasticsearch-head/_site/app.js #把localhost改为ip this.base_uri=this.config.base_uri||this.prefs.get( "app-base_uri" )|| "http://localhost:9200" ; this.base_uri=this.config.base_uri||this.prefs.get( "app-base_uri" )|| "http://192.168.53.108:9200" ; 1 2 3 4 5 6 7 8 9 10 11 [root@host-192-168-53-108elasticsearch- head ] #vim/usr/local/elasticsearch-head/Gruntfile.js connect:{ server:{ options:{ hostname : "0.0.0.0" , #添加此行 port:9100, base: '.' , keepalive: true } } } 1 2 3 4 [root@host-192-168-53-108elasticsearch- head ] #gruntserver& [root@host-192-168-53-108elasticsearch- head ] #echo"cd/usr/local/elasticsearch-head;gruntserver&">>/etc/rc.local [root@host-192-168-53-108elasticsearch- head ] #cd [root@host-192-168-53-108~] #wgethttps://artifacts.elastic.co/downloads/logstash/logstash-5.5.0.rpm 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@host-192-168-53-108~] #vim/etc/logstash/conf.d/system.conf input{ file { path=> "/var/log/messages" type => "systemlog" start_position=> "beginning" stat_interval=> "2" } } output{ elasticsearch{ hosts=>[ "192.168.53.108:9200" ] index=> "logstash-systemlog-%{+YYYY.MM.dd}" } } 1 [root@host-192-168-53-108~] #/usr/share/logstash/bin/logstash-f/etc/logstash/conf.d/system.conf 1 2 #在Elasticsearch中查看 #浏览器访问http://192.168.53.108:9100/选择基本查询搜素 1 2 [root@host-192-168-53-108~] #wgethttps://artifacts.elastic.co/downloads/kibana/kibana-5.5.0-x86_64.rpm [root@host-192-168-53-108~] #rpm-ivhkibana-5.5.0-x86_64.rpm 1 2 3 4 [root@host-192-168-53-108~] #cat/etc/kibana/kibana.yml|grep-v'^#'|grep-v^$ server.port:5601 server.host: "0.0.0.0" elasticsearch.url: "http://elk1:9200" 1 2 [root@host-192-168-53-108~] #/etc/init.d/kibanastart [root@host-192-168-53-108~] #chkconfig--addkibana 本文转自谢无赖51CTO博客,原文链接:http://blog.51cto.com/xieping/1951765,如需转载请自行联系原作者

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

docker 入门操作与本地厂库

docker 自诞生以来就是业内讨论得很火的一个话题,讨论程度仅此于openstack,后期应该会持续更新一些关于docker的内容: docker是什么:简单来说docker 是软件工业的集装箱技术,可以实现相互隔离快速打包部署功能。 docker的安装和基本命令: 环境: centos 7 docker安装: 1 [root@xiaoluosrc] #yuminstalldocker-io-y ##docker三个基本概念我之见: 1、镜像:可以理解成一个简单的系统,在上面可以部署和运行东西,用镜像可以启动一个容器。 2、容器:一个容器代表一个独立的任务,各容器之前相互隔离运行。 3、厂库:存放镜像的地方。 查看镜像: 1 2 3 4 [root@xiaoluosrc] #dockerimages REPOSITORYTAGIMAGE ID CREATEDVIRTUALSIZE centoslatest 60e65a8e4030 8 weeksago 196.6 MB ubuntu 14.04 d55e68e6cc9c 11 weeksago 187.9 MB *TAG:镜像的标识,当使用push不加别的版本,默认使用的是latest. IMAGE ID:镜像的唯一标识 查看可以下载镜像: 1 [root@xiaoluosrc] #dockersearchcentos 下载镜像可以docker pull xxx 从库里下载: 交互模式下启动docker: 1 2 [root@xiaoluosrc] #dockerexec-itcentos/bin/bash [root@ 73aaba6e0cd1 / ] # 启动docker: 1 2 3 4 5 [root@localhost~] #dockerrun-d-p2222:22--namebasecsphere/centos:7.193e712c9d91467c0748961685e5453a7cd50898212191a762a36c6e933dbd539 * - d后台启动 - p本机端口 2222 映射到docker内部的 22 口(当然前提镜像是提前构建好,后期会讲到) - - name给容器起一个别名base 镜像名称csphere / centos: 7.1 查看正在启动的容器: 1 2 3 [root@localhost~] #dockerps CONTAINER ID IMAGECOMMANDCREATEDSTATUSPORTSNAMES 93e712c9d914 csphere / centos: 7.1 "/usr/bin/supervisord" AboutaminuteagoUpAboutaminute 0.0 . 0.0 : 2222 - > 22 / tcpbase *查看所有的容器使用docker ps -a 删除容器:docker rm93e712c9d914 (删除正在运行的容器docker rm f) docker私有厂库: 当我们使用docker pull的时候默认是从官方的镜像去下载的,在我们环境中要是搭建一个本地的厂库存放我们的镜像就在合适不过了: 步骤: 1、下载一个registry容器,官方的images有时候被墙,我这里用的是灵雀云的镜像: 1 [root@localhost~] #dockerpullindex.alauda.cn/library/registry 2、重命名一个镜像:测试用 1 [root@localhost~] #dockertag7e4f044162b7192.168.63.198:5000/test *把镜像ID为7e4f044162b7定义别名192.168.63.198:5000/test 1 2 3 4 5 6 7 8 [root@localhostnative] #dockerimages REPOSITORYTAGIMAGE ID CREATEDVIRTUALSIZE 192.168 . 63.198 : 5000 / testlatest 7e4f044162b7 8 daysago 724.9 MB csphere / mysql 5.5 7e4f044162b7 8 daysago 724.9 MB csphere / php - fpm 5.4 f149fdc3bb11 8 daysago 684.8 MB csphere / centos 7.1 e3570ed66dc9 8 daysago 591.3 MB index.alauda.cn / library / registrylatest 07d93e41c370 4 weeksago 422.8 MB docker.io / centoscentos7. 1.1503 fab4b1df8eb1 4 monthsago 212.1 MB 3、本地启动本地镜像厂库: 1 [root@localhost~] #dockerrun-d-p5000:5000-v/opt/data/registry/:/tmp/registry-dev07d93e41c370 4、修改配置文件/etc/sysconf/docker: 1 2 打开 / etc / sysconfig / docker,找到OPTIONS这一行,取消注释并修改如下: OPTIONS = '--selinux-enabled--insecure-registry=yourip:5000' **不然会报如下类似错: 1 2 3 4 unabletopingregistryendpoint https: / / yourip: 5000 / v0 / v2pingattemptfailedwitherror:Gethttps: / / yourip: 5000 / v2 / :EOF v1pingattemptfailedwitherror:Gethttps: / / yourop: 5000 / v1 / _ping:EOF 5、提交镜像到本地库: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 [root@localhostnative] #dockerpush192.168.63.198:5000/test Thepushreferstoarepository[ 192.168 . 63.198 : 5000 / test]( len : 1 ) Sendingimage list Pushingrepository 192.168 . 63.198 : 5000 / test( 1 tags) f1b10cd84249:Imagesuccessfullypushed 172633e38420 :Imagesuccessfullypushed fab4b1df8eb1:Imagesuccessfullypushed 7911a8421c83 :Imagesuccessfullypushed af42609f6313:Imagesuccessfullypushed fa48118fc839:Imagesuccessfullypushed b7ca1c16fd68:Imagesuccessfullypushed fca316033a3c:Imagesuccessfullypushed 09f10030ab42 :Imagesuccessfullypushed dc888ecebd54:Imagesuccessfullypushed 519dde82a4cc :Imagesuccessfullypushed 832a31216b14 :Imagesuccessfullypushed e3570ed66dc9:Imagesuccessfullypushed e65974137a30:Imagesuccessfullypushed 2752603711a9 :Imagesuccessfullypushed f027aaa7d0db:Imagesuccessfullypushed 6b59cfa21ac8 :Imagesuccessfullypushed 94d6cbee9151 :Imagesuccessfullypushed 5caacec189e1 :Imagesuccessfullypushed 255629e3621b :Imagesuccessfullypushed 3ba1834f6adf :Imagesuccessfullypushed 7e4f044162b7 :Imagesuccessfullypushed Pushingtag for rev[ 7e4f044162b7 ]on{ http: / / 192.168 . 63.198 : 5000 / v1 / repositories / test / tags / latest} 6、上传成功检查: 1 2 [root@localhostregistry] #curl-XGEThttp://192.168.63.198:5000/v1/search { "num_results" : 1 , "query" :" "," results ":[{" description ":" "," name ":" library / test"}]} 到此本地厂库创建完成。 本文转自 小罗ge11 51CTO博客,原文链接:http://blog.51cto.com/xiaoluoge/1745360,如需转载请自行联系原作者

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

OpenStack入门修炼之环境准备(6)

1.安装仓库 yum install -y centos-release-openstack-newton 2.安装Openstack客户端 yum install -y python-openstackclient yum install -y openstack-selinux tips:openstack-selinux可以自动配置selinux,保证不影响实验的环境 3.安装数据库 yum install -y mariadb mariadb-server python2-PyMySQL tips:除了组件horizon之外,其余openstack的组件都需要依赖数据库 对数据库进行配置: vim /etc/my.cnf/openstack.cnf [mysqld] bind-address = 192.168.56.11 (绑定ip地址) default-storage-engine = innodb (默认存储引擎) innodb_file_per_table (使用独享表空间) max_connections = 4096 (最大连接数) collation-server = utf8_general_ci (字符集设置) character-set-server = utf8 4.安装消息队列RabbitMQ 消息队列用于OpenStack各个组件通信 yum install -y rabbitmq-server 5.安装memcached memcached作为缓存模块,用于在获取令牌(token)时进行缓存,减少对数据库的访问 yum install -y memcached python-memcached 6.服务安装 ①认证服务keystone,wsgi是用于apache与pythone进行通信的模块 yum install -y openstack-keystone httpd mod_wsgi ②镜像服务glance yum install -y openstack-glance ③计算服务nova yum install -y openstack-nova-api openstack-nova-conductor \ openstack-nova-console openstack-nova-novncproxy \ openstack-nova-scheduler ④网络服务neutron yum install -y openstack-neutron openstack-neutron-ml2 \ openstack-neutron-linuxbridge ebtables 7.两台服务器时间同步 时间不同步,会导致虚拟机无法创建成功 [root@linux-node1 ~]# ntpdate time1.aliyun.com 4 Dec 09:52:32 ntpdate[21469]: step time server 115.28.122.198 offset -28368.811357 sec [root@linux-node1 ~]# crontab -e */5 * * * * /usr/sbin/ntpdate time1.aliyun.com &>/dev/null 本文转自 IT_外卖小哥 51CTO博客,原文链接:http://blog.51cto.com/jinlong/2049447

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

Docker入门与七牛kirk工具

一、Docker的实现原理和技术前景 Docker技术是一门容器技术,于2013年正式开源发行,现在它已经成为了目前最流行的虚拟化技术,Docker的优点是“轻量型”,“可移植”,“自给自足”。 Docker大略执行思想如下: 1)启动一个基础镜像(image),比如centos或者ubantu; 2)Docker可以根据这个基础的image来构建成一个容器(container); 3)在这个容器上,我们可以像在普通的服务器上编写需要的代码,并且启动编写好的服务(service); 4)将这些已经编写好的、有服务的容器重新打包成镜像,这个镜像可以备用也可以放在网络上分享。 从上面几个操作步骤来看,Docker技术与虚拟机技术有类似的效果,同样达到在一个宿主机上运行多个子服务器的目的,而且每一个容器之间互不干扰,就像Docker的标志一样:一个大鲸鱼背上面有诸多个集装箱,这些集装箱就是装载各种服务的容器们,而这个大鲸鱼就是docker,它可以同时负载多个容器并且让这些容器平稳正常的运行,不管如此,docker容器的运行效率又是虚拟机的好多倍,可以迅速提升响应速度也是Docker备受开发人员和运维人员青睐的原因之一。Docker的引擎开发、二次管理以及安全策略也是时下非常火热的技术,可以说Docker 给运维带来了革命性的改变,大有深入乃至挖掘的必要性! 二、Docker的安装以及kirk的安装 Docker的安装对宿主机的内核有比较硬性的要求,Docker要求宿主机的内核是3.1.10。也就是说Docker应该工作在Centos 7以上的版本里,而不是我们传统购买的服务器Centos 6.5版本。由于目前阿里云和金山云的Centos 6.5默认自带的内核都是2.6.32,所以如果要在以上两个厂家的Centos 6.5里正常使用Docker的话需要我们自己升级内核。 在Centos 7里安装Docker是十分简单的,只需要#yum install Docker,而启动Docker也是很简单的:#service Docker start,在运行之后我们可以查看一下当前Docker的版本: 如果能像如图那样成功显示Docker的版本,即代表Docker已经安装且运行成功。 Kirk是七牛云提供的一个管理docker容器的工具,我们可以把七牛的账号用于kirk,使kirk专门存储内部的模块镜像,并且可以调用这些docker服务,它对应linux下载包的地址是http://7xqd3r.com1.z0.glb.clouddn.com/kirk/beta/latest/linux-amd64/kirk.tar.gz,下载完毕之后直接拆包解压即可使用。 三、整个P2P的服务启动过程 下面我将以P2P为例,演示一下启动P2P服务的过程: 当我们从开发人员手里获取到docker file,并且将其build成一个可使用的镜像之后。 1)登陆kirk账户 在七牛网站右上角的“个人面板”点击“密钥管理”,就会看到一对密码分别是AK/SK,如图所示: 在服务器端输入#kirk login就是登陆kirk账号,这里就对应输入AK和SK,输入正确的话就是提示登入成功。 2)使用#kirk images来查看kirk里所有的镜像: 看到现在的kirk里面已经有不少的docker P2P镜像,而且后面分别是这些镜像建立的时间点,我们这里需要的是p2prelay服务,于是我们只需要启动它,但是要注意,在docker里一个镜像是可以生成多个容器的,这些容器在出生阶段是一模一样的。但是在kirk里一个镜像只能生成一个服务(service),如果重复的打开同一个服务,会报错ERROR fail to start service: {"code":400,"codeName":"E30014","description":"current state is invalid to start service"} ,查看当前运行容器的命令是#kirk ps,因为这是一个新装的机器,所以#kirk ps结果为空。 我们要启动服务的话,需要先启动七牛的工具,#kirk service qiniu-tool,然后再如法炮制分别启动对应的服务,比如启动relay-1、relay-2、gms等等,如图所示: 如果这个时候想进入到relay-1这个容器里面看一下,就使用#kirk ssh relay-1这个命令: 这里发现hostname发生了变化,变成的10-128-128-113恰巧就是relay-1对应的那个container编码,在容器里这个P2PRelay已经完全启动了。 如果想要退出当前容器,使用命令#exit就返回宿主机,继续宿主机的操作。 四、校验 启动服务之后,我们登陆到容器relay-1,容器就相当于是一个虚拟机,那么在这个小虚拟机里是可以查看进程的,使用#ps –ef一下可以查看进程,而且还可检查一下端口以及看一下其他的服务: 由于这台P2P只是试验,所以bind count和angets num都是零,但是依旧可以看出服务和端口已经是正确的了。 但是目前七牛的kirk还是有一点问题:它只能把容器挂载到宿主机的文件夹上,而不能实现把容器挂载到其他云服务器的文件夹上,这一点在模块的升级上有所不便,与七牛技术人员沟通,他们反馈目前在做一个类似网络云盘共享的开发,预计将来可以通过此途径解决这个问题。但是在目前阶段,如果涉及到模块的更新,就需要重新编写一个image,重新build成镜像,这一点与原有的从挂载盘上拷贝更新脚本有很大的不同。 五、对比 在传统的运维部署下,运维人员需要做的事情如下: 1)购买云服务器,对应填写服务器ip表格; 2)初始化服务器,金山区服务器还需要挂载数据盘; 3)检查角色,运行模块安装脚本; 4)将服务器内网ip添加到zk配置里; 5)启动进程,检查zk、模块、看门狗是否都已经启动; 6)检查日志情况; 而在docker-kirk的环境下,运维部署模块的步骤: 1)购买云服务器,对应填写服务器ip表格; 2) 运维人员得到开发人员的dockerfile,将其build成一个镜像; 3)使用kirk上传其镜像到七牛云; 4)kirk启动对应的服务; 5)根据不同的ip需求配置ip端口; 6)登陆容器内部,检查进程、zk、看门狗; 7)检查日志情况。 从上所见,在docker-kirk过程里省去了脚本这一步,传统模式下由于开发人员模块编写语言各有不同,有的是java模块,有的是tomcat模块,因此在启动上和后台所需环境版本上均有差异,有的甚至在看门狗的配置上都有差异,而这些差异都是需要运维人员手动去修改脚本,而使用了docker-kirk,就可以将2、3、4步整合成一个脚本,然后通过运行脚本直接将已经配置好的镜像生成到容器里部署到服务器里使用,这样更加便捷从而提升了效率。 但是kirk的ip配置是一个难点,而且批量端口影射服务尚不完善,这些都有待七牛开发人员后续跟进补全。 六、总结 如果引用Docker技术的话,我们将来可以依旧使用阿里云、金山云的跳板机去登录相对性能较低的云服务器,同时在服务器上安装七牛的kirk工具,同时根据不同的模块需求购买对应性能的七牛云服务,七牛云服务提供硬件环境,kirk作为工具,这样两者双剑合并来增删改用各种Docker镜像,从而启动各种进程。 目前测试看来Docker的优点如下: 1)保证线上与测试的环境一致,省去了中间配置各种环境的麻烦,甚至可以在同一个服务器上安装不同独立的服务; 2)快速部署,传统的部署模式是:安装(包管理工具或者源码包编译)->配置->运行;Docker的部署模式是:复制->运行; 3)对云计算更加方便和友好。 而其缺点如下: 1)目前尚不支持传统意义上的挂载,升级的时候需要重做镜像; 2)网络机制比较复杂,导致其大型部署比较麻烦,甚至会出现失控情况; 3)一些运维常见功能比如crontab需要事前增加到Dockerfile里; 4)目前kirk不支持退出当前账号的功能; 本文转自 苏幕遮618 51CTO博客,原文链接:http://blog.51cto.com/chenx1242/1846337

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

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

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