Sunday, October 23, 2016

JUnit入门教程

下载JUnit.jar和hamcrest.jar
 许多IDE都自带了JUnit,但是并不推荐使用,  我们自己动手下载Jar包(不推荐使用的原因后面会说明)
 点击http://www.junit.org可以下载到最新版本的JUnit,目前最新版本是4.11。进入官网选择Download and Install guide,
然后选择Plain-old JAR下的junit.jar,找到最新的4.11版本,下载jar包.
  点击http://code.google.com/p/hamcrest/downloads/list下载最新的hamcrest-1.3.zip,解压.找到hamcrest-core-1.3.jar
    然后在项目中引用junit-4.11.jarhamcrest-core-1.3.jar,这样你就可以使用JUnit编写单元测试代码了.


三、简单的例子
    记得在几乎每本语言教学书上都能找到HelloWorld这个入门代码。今天在这里,我们也从一个简单到根本不用单元测试的例子入手。四则运算。
    第一步:建立项目引用junit-4.11.jarhamcrest-core-1.3.jar
    第二步:编写Calculator类,代码如下:
[java] view plain copy

  1.   
  2. public class Calculator {   
  3.   
  4.     public int plus(int x, int y) {  
  5.         return x + y;  
  6.     }  
  7.   
  8.     public int subtraction(int x, int y) {  
  9.         return x - y;  
  10.     }  
  11.   
  12.     public int multiplication(int x, int y) {  
  13.         return x * y;  
  14.     }  
  15.   
  16.     public int division(int x, int y) {  
  17.         return x / y;  
  18.     }  
  19.   
  20. }   
    第三步:编写单元测试类,代码如下:
[java] view plain copy
  1.  
  2.   
  3. import static org.junit.Assert.*; //注意这边,静态导入  
  4.   
  5. import org.junit.Ignore;  
  6. import org.junit.Test;  
  7.   

  8.   
  9. public class TestCalculator {  
  10.   
  11.     @Test  
  12.     public void testPlus() {  
  13.         Calculator cal = new Calculator();  
  14.         assertEquals(cal.plus(55), 10);  
  15.     }  
  16.   
  17.     @Test  
  18.     public void testSubtraction() {  
  19.         Calculator cal = new Calculator();  
  20.         assertEquals(cal.subtraction(55), 0);  
  21.     }  
  22.   
  23.     @Ignore  
  24.     @Test  
  25.     public void testMultiplication() {  
  26.         Calculator cal = new Calculator();  
  27.         assertTrue(cal.multiplication(55) > 20);  
  28.     }  
  29.   
  30.     @Test(expected = java.lang.ArithmeticException.class, timeout = 50)  
  31.     public void testDivision() {  
  32.         Calculator cal = new Calculator();  
  33.         assertEquals(cal.division(80), 4); //大家注意看,除数是0  
  34.     }  
  35. }  

    第四步:测试,在这里,我用的是MyEclipse,在TestCalculator类上右键找到Run As 下的JUnit Test,点击然后就开始测试了
    第五步:观察测试结果,在这里我测试都是正确的,

但是每个测试方法下都new一个Calculator对象很浪费资源,假如有80个测试方法呢?所以接下来我们要使用@BeforeClass,代码如下:
[java] view plain copy

  1.   
  2. import static org.junit.Assert.*;  
  3.   
  4. import org.junit.BeforeClass;  
  5. import org.junit.Ignore;  
  6. import org.junit.Test;  
  7.   
  8. import com.zjw.junit4.Calculator;  
  9.   
  10. public class TestCalculator {  
  11.       
  12.     private static Calculator cal;  
  13.           
  14.     @BeforeClass  
  15.     public static void beforeClass(){ //静态方法  
  16.         cal=new Calculator();  
  17.     }  
  18.       
  19.     @Test  
  20.     public void testPlus() {  
  21.         assertEquals(cal.plus(55), 10);  
  22.     }  
  23.   
  24.     @Test  
  25.     public void testSubtraction() {  
  26.         assertEquals(cal.subtraction(55), 0);  
  27.     }  
  28.   
  29.     @Ignore  
  30.     @Test  
  31.     public void testMultiplication() {  
  32.         assertTrue(cal.multiplication(55) > 20);  
  33.     }  
  34.   
  35.     @Test(expected = java.lang.ArithmeticException.class, timeout = 50)  
  36.     public void testDivision() {  
  37.         assertEquals(cal.division(80), 4);  
  38.     }  
  39. }  

Monday, August 8, 2016

Install Nginx on Ubuntu 16.04

Introduction

Nginx is one of the most popular web servers in the world and is responsible for hosting some of the largest and highest-traffic sites on the internet. It is more resource-friendly than Apache in most cases and can be used as a web server or a reverse proxy.
In this guide, we'll discuss how to get Nginx installed on your Ubuntu 16.04 server.

Prerequisites

Before you begin this guide, you should have a regular, non-root user with sudo privileges configured on your server. You can learn how to configure a regular user account by following our initial server setup guide for Ubuntu 16.04.
When you have an account available, log in as your non-root user to begin.

Step 1: Install Nginx

Nginx is available in Ubuntu's default repositories, so the installation is rather straight forward.
Since this is our first interaction with the apt packaging system in this session, we will update our local package index so that we have access to the most recent package listings. Afterwards, we can installnginx:
  • sudo apt-get update
  • sudo apt-get install nginx
After accepting the procedure, apt-get will install Nginx and any required dependencies to your server.

Step 2: Adjust the Firewall

Before we can test Nginx, we need to reconfigure our firewall software to allow access to the service. Nginx registers itself as a service with ufw, our firewall, upon installation. This makes it rather easy to allow Nginx access.
We can list the applications configurations that ufw knows how to work with by typing:
  • sudo ufw app list
You should get a listing of the application profiles:
Output
Available applications: Nginx Full Nginx HTTP Nginx HTTPS OpenSSH
As you can see, there are three profiles available for Nginx:
  • Nginx Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
  • Nginx HTTP: This profile opens only port 80 (normal, unencrypted web traffic)
  • Nginx HTTPS: This profile opens only port 443 (TLS/SSL encrypted traffic)
It is recommended that you enable the most restrictive profile that will still allow the traffic you've configured. Since we haven't configured SSL for our server yet, in this guide, we will only need to allow traffic on port 80.
You can enable this by typing:
  • sudo ufw allow 'Nginx HTTP'
You can verify the change by typing:
  • sudo ufw status
You should see HTTP traffic allowed in the displayed output:
Output
Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Nginx HTTP ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Nginx HTTP (v6) ALLOW Anywhere (v6)

Step 3: Check your Web Server

At the end of the installation process, Ubuntu 16.04 starts Nginx. The web server should already be up and running.
We can check with the systemd init system to make sure the service is running by typing:
  • systemctl status nginx
Output
● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2016-04-18 16:14:00 EDT; 4min 2s ago Main PID: 12857 (nginx) CGroup: /system.slice/nginx.service ├─12857 nginx: master process /usr/sbin/nginx -g daemon on; master_process on └─12858 nginx: worker process
As you can see above, the service appears to have started successfully. However, the best way to test this is to actually request a page from Nginx.
You can access the default Nginx landing page to confirm that the software is running properly. You can access this through your server's domain name or IP address.
If you do not have a domain name set up for your server, you can learn how to set up a domain with DigitalOcean here.
If you do not want to set up a domain name for your server, you can use your server's public IP address. If you do not know your server's IP address, you can get it a few different ways from the command line.
Try typing this at your server's command prompt:
  • ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'
You will get back a few lines. You can try each in your web browser to see if they work.
An alternative is typing this, which should give you your public IP address as seen from another location on the internet:
  • sudo apt-get install curl
  • curl -4 icanhazip.com
When you have your server's IP address or domain, enter it into your browser's address bar:
http://server_domain_or_IP
You should see the default Nginx landing page, which should look something like this:
Nginx default page
This page is simply included with Nginx to show you that the server is running correctly.

Step 4: Manage the Nginx Process

Now that you have your web server up and running, we can go over some basic management commands.
To stop your web server, you can type:
  • sudo systemctl stop nginx
To start the web server when it is stopped, type:
  • sudo systemctl start nginx
To stop and then start the service again, type:
  • sudo systemctl restart nginx
If you are simply making configuration changes, Nginx can often reload without dropping connections. To do this, this command can be used:
  • sudo systemctl reload nginx
By default, Nginx is configured to start automatically when the server boots. If this is not what you want, you can disable this behavior by typing:
  • sudo systemctl disable nginx
To re-enable the service to start up at boot, you can type:
  • sudo systemctl enable nginx

Step 5: Get Familiar with Important Nginx Files and Directories

Now that you know how to manage the service itself, you should take a few minutes to familiarize yourself with a few important directories and files.

Content

  • /var/www/html: The actual web content, which by default only consists of the default Nginx page you saw earlier, is served out of the /var/www/html directory. This can be changed by altering Nginx configuration files.

Server Configuration

  • /etc/nginx: The nginx configuration directory. All of the Nginx configuration files reside here.
  • /etc/nginx/nginx.conf: The main Nginx configuration file. This can be modified to make changes to the Nginx global configuraiton.
  • /etc/nginx/sites-available: The directory where per-site "server blocks" can be stored. Nginx will not use the configuration files found in this directory unless they are linked to the sites-enabled directory (see below). Typically, all server block configuration is done in this directory, and then enabled by linking to the other directory.
  • /etc/nginx/sites-enabled/: The directory where enabled per-site "server blocks" are stored. Typically, these are created by linking to configuration files found in the sites-availabledirectory.
  • /etc/nginx/snippets: This directory contains configuration fragments that can be included elsewhere in the Nginx configuration. Potentially repeatable configuration segments are good candidates for refactoring into snippets.

Server Logs

  • /var/log/nginx/access.log: Every request to your web server is recorded in this log file unless Nginx is configured to do otherwise.
  • /var/log/nginx/error.log: Any Nginx errors will be recorded in this log.

Conclusion

Now that you have your web server installed, you have many options for the type of content to serve and the technologies you want to use to create a richer experience.

Sunday, July 3, 2016

gevent + bottle 异步处理

from gevent import monkey; monkey.patch_all()
import bottle
import gevent

def worker():
    print ('worker called')
    gevent.sleep(10)
    print ('worker finished after 10 secondss')

@bottle.route('/')
def index():
    gevent.spawn(worker)
    return "ok"

def main():finish
    bottle.run(host='0.0.0.0',port=8080, server="gevent")

if __name__ == '__main__':
    main()

Friday, July 1, 2016

curl 测速

curl -o /dev/null -s -w 'DNS:%{time_namelookup}\nConnect:%{time_connect}\nStart:%{time_starttransfer}\nTotal:%{time_total}\nSpeed:%{speed_download} byte/s' https://xxx.com/
返回结果:
DNS:0.030
Connect:0.078
Start:0.503
Total:0.515
Speed:60306.000 byte/s

SSL延迟有多大?

据说,Netscape公司当年设计SSL协议的时候,有人提过,将互联网所有链接都变成HTTPs开头的加密链接。
这个建议没有得到采纳,原因之一是HTTPs链接比不加密的HTTP链接慢很多。(另一个原因好像是,HTTPs链接默认不能缓存。)
自从我知道这个掌故以后,脑袋中就有一个观念:HTTPs链接很慢。但是,它到底有多慢,我并没有一个精确的概念。直到今天我从一篇文章中,学到了测量HTTPs链接耗时的方法。
首先我解释一下,为什么HTTPs链接比较慢。
HTTPs链接和HTTP链接都建立在TCP协议之上。HTTP链接比较单纯,使用三个握手数据包建立连接之后,就可以发送内容数据了。
tcp handshake
上图中,客户端首先发送SYN数据包,然后服务器发送SYN+ACK数据包,最后客户端发送ACK数据包,接下来就可以发送内容了。这三个数据包的发送过程,叫做TCP握手。
再来看HTTPs链接,它也采用TCP协议发送数据,所以它也需要上面的这三步握手过程。而且,在这三步结束以后,它还有一个SSL握手。
总结一下,就是下面这两个式子。
HTTP耗时 = TCP握手
HTTPs耗时 = TCP握手 + SSL握手
所以,HTTPs肯定比HTTP耗时,这就叫SSL延迟。
命令行工具curl有一个w参数,可以用来测量TCP握手和SSL握手的具体耗时,以访问支付宝为例。


$ curl -w "TCP handshake: %{time_connect}, SSL handshake: %{time_appconnect}\n" -so /dev/null https://www.alipay.com

TCP handshake: 0.022, SSL handshake: 0.064

上面命令中的w参数表示指定输出格式,time_connect变量表示TCP握手的耗时,time_appconnect变量表示SSL握手的耗时,s参数和o参数用来关闭标准输出。
从运行结果可以看到,SSL握手的耗时(64毫秒)大概是TCP握手(22毫秒)的三倍。也就是说,在建立连接的阶段,HTTPs链接比HTTP链接要长3倍的时间,具体数字取决于CPU的快慢和网络状况。
所以,如果是对安全性要求不高的场合,为了提高网页性能,建议不要采用保密强度很高的数字证书。一般场合下,1024位的证书已经足够了,2048位和4096位的证书将进一步延长SSL握手的耗时。

Monday, June 27, 2016

webbench测试网站

由于要搞网站压力测试就准备在ubuntu下安装webbench

首先webbench是依赖于ctags,在shell中只需输入ctags即知有没有安装,如果没有要先安装ctags
如果你的源中有ctags很容易
Shell代码  
  1. sudo apt-get install ctags  

即可安装
我的源里没有,要手动:

Shell代码  
  1. wget http://prdownloads.sourceforge.net/ctags/ctags-5.8.tar.gz  
  2. tar zxvf ctags-5.8.tar.gz  
  3. cd ctags-5.8  
  4. ./configure  
  5. make  
  6. sudo make install  

到此ctags安装完毕
下载webbench:
Shell代码  
  1. wget http://www.linuxidc.com/system/systembak/webbench/webbench-1.5.tar.gz  
  2. tar zxvf webbench-1.5.tar.gz   
  3. make  
  4. sudo make install  

即可安装成功
其中
ctags:469K
webbench:7.5K
真的感到linux软件的强大精悍呀

用法:

Shell代码  
  1. webbench -c 100 -t 10 http://www.itye.com/  
  
其中:
-c表示并发数,
-t表示时间(秒)
 注意url结尾一定要加上/

安装后发现其实apache自带的ab非常好用
Shell代码  
  1. ab -c 1000 -n 100 http://www.iteye.com/index.php  
  2. 这个表示同时处理1000个请求并运行100次index.php文件.