现代的Java开发真的和我当年认识的很不一样了,这三篇文章非常值得一读:

http://blog.paralleluniverse.co/2014/05/01/modern-java/
http://blog.paralleluniverse.co/2014/05/08/modern-java-pt2/
http://blog.paralleluniverse.co/2014/05/15/modern-java-pt3/

下面是一个java写的echo server。基于NIO2的callback和Quasar的fiber,比mina和netty之流好看实在太多了。而且同样是异步IO实现的,应该性能不差的。

package echo_server;

import co.paralleluniverse.fibers.*;
import co.paralleluniverse.fibers.io.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
    static final int PORT = 1234;

    public static void main(String[] args) throws Exception {
        new Fiber(() -> {
            try {
                FiberServerSocketChannel socket = FiberServerSocketChannel.open().bind(new InetSocketAddress(PORT));
                System.out.println("started");
                for (;;) {
                    FiberSocketChannel ch = socket.accept();
                    new Fiber(() -> {
                        try {
                            ByteBuffer buf = ByteBuffer.allocateDirect(1024);
                            while (true) {
                                buf.clear();
                                ch.read(buf);
                                buf.flip();
                                ch.write(buf);
                            }
                        } catch (IOException e) {
                            LOGGER.error("client fiber failed", e);
                        }
                    }).start();
                }
            } catch (IOException e) {
                LOGGER.error("main fiber failed", e);
            }
        }).start();
        Thread.sleep(Long.MAX_VALUE);
    }
}

用telnet 127.0.0.1 1234连上去之后,你输入什么它就返回什么。支持多个客户端同时连接的。这个是配套的build.gradle文件

apply plugin: 'java'
apply plugin: 'application'

sourceCompatibility = '1.8'

mainClassName = 'echo_server.Main'

repositories {
    mavenCentral()
}

configurations {
    quasar
}

dependencies {
    compile "co.paralleluniverse:quasar-core:0.6.0:jdk8"
    quasar "co.paralleluniverse:quasar-core:0.6.0:jdk8"
    compile "org.slf4j:slf4j-api:1.7.7"
    runtime "org.slf4j:slf4j-jdk14:1.7.7"
    testCompile 'junit:junit:4.11'
}

run {
    jvmArgs "-javaagent:${configurations.quasar.iterator().next()}"
}

特别提一下IntelliJ,使用非常方便,直接可以打开gradle的项目。


taowen
4.1k 声望1.4k 粉丝

Go开发者们请加入我们,滴滴出行平台技术部 taowen@didichuxing.com