使用Java创建对象池

时间:2015-01-28 18:06:53

标签: java connection-pooling apache-commons apache-commons-net apache-commons-pool

前一段时间我创建了一个创建套接字连接的程序,并将其输入汇集到我们遗留服务器的单个telnet连接。该项目的目标是为遗留数据库创建前端,并最终迁移到现代数据库。我以一种我认为可以扩展到多个telnet连接的方式进行设置。那么现在是时候让我开始使用2-4连接到旧服务器,它不起作用。它总是将输入发送到最后建立的连接。这就是我所做的:

第1类 - ServerConsole

package serverconsole;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 *
 * @author Andrew
 */
public class ServerConsole {

    public static ArrayList<Boolean> busy = new ArrayList();
    public static ArrayList<MvTelnet> telnet = new ArrayList();
    static final Logger log = Logger.getLogger("errors");
    static FileHandler fh;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(5500)) {
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    if (serverSocket != null) {
                        try {
                            serverSocket.close();
                        } catch (IOException ex) {
                            Logger.getLogger(ServerConsole.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }, "Shutdown-thread"));

            fh = new FileHandler("/mnt/javaprograms/ServerConsole/errors.log");
            log.addHandler(fh);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);

            for(int i=0; i<2; i++) {
                busy.add(false);
                telnet.add(null);
            }

            while (true) {
                new MultiServerThread(serverSocket.accept()).start();
            }
        } catch (IOException e) {
            System.err.println(e);
            System.exit(-1);
        }
    }

    public static void log(String str) {
        log.info(str);
    }
}

第2类 - MultiServerThread

package serverconsole;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author Andrew
 */
public class MultiServerThread extends Thread {

    private Socket socket = null;

    public MultiServerThread(Socket socket) throws IOException {
        super("MultiServerThread");
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
            ;) {
            String input, output;
            while (true) {
                input = in.readLine();
                if (input.equals("Close")) {
                    break;
                }
                boolean written = false;
                while(written == false) {
                    for (int i=0;i < ServerConsole.busy.size(); i++) {
                        if (ServerConsole.busy.get(i) == false) {
                            ServerConsole.busy.set(i, true);
                            if (ServerConsole.telnet.get(i) == null) {
                                ServerConsole.telnet.set(i, new MvTelnet());
                            }
                            String response = ServerConsole.telnet.get(i).write(input);
                            out.println(response);
                            written = true;
                            ServerConsole.busy.set(i, false);
                            break;
                        }
                    }
                }
            }
            socket.close();
        } catch (IOException e) {
            ServerConsole.log(e.getMessage());
        }
    }
}

第3类 - MvTelnet     包serverconsole;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 *
 * @author Andrew
 */
public class MvTelnet {
    static TelnetClient tc = null;
    private static DataInputStream in = null;
    private static DataOutputStream out = null;
    static String response = null;
    static FileWriter fstream = null;
    static BufferedWriter bout = null;

    public MvTelnet() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH-mm-ss");
        try {
            tc = new TelnetClient();
            bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/mnt/javaprograms/ServerConsole/log"+sdf.format(cal.getTime())+".txt"), "UTF-8"));
            TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
            EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
            SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
            try {
                tc.addOptionHandler(ttopt);
                tc.addOptionHandler(echoopt);
                tc.addOptionHandler(gaopt);
            } catch (InvalidTelnetOptionException e) {
                ServerConsole.log(e.getMessage());
            }
            tc.connect("192.168.1.8", 2010);
            in = new DataInputStream(tc.getInputStream());
            out = new DataOutputStream(tc.getOutputStream());
            logon(true);
        } catch (IOException ex) {
            ServerConsole.log(ex.getMessage());
        }
    }

    public static String write(String command) throws IOException {
        command = command + "\n";
        byte[] comm = command.getBytes();
        out.write(comm);
        out.flush();
        response = in.readLine();
        bout.write(response+"\n");
        response = in.readLine();
        bout.write(response+"\n");
        if (response.contains("[] Connect time")) {
            logon(false);
            out.write(comm);
            out.flush();
            response = in.readLine();
            bout.write(response+"\n");
            response = in.readLine();
            bout.write(response+"\n");
        }
        bout.flush();
        return response;
    }

    public static void close() throws IOException {
        write("...\n");
        write("OFF\n");
        tc.disconnect();
    }

    private static void logon(boolean choice) throws IOException {
        String loginString = "JAVA-TRANS\n";
        byte[] logon = loginString.getBytes();
        if (choice == true) {
            response = in.readLine();
            bout.write(response+"\n");
            bout.flush();
            response = in.readLine();
            bout.write(response+"\n");
            bout.flush();
            out.write(logon);
            out.flush();
            response = in.readLine();
            bout.write(response+"\n");
            bout.flush();
            response = in.readLine();
            bout.write(response+"\n");
            bout.flush();
            if (!response.contains("OK")) {
                out.write(logon);
                out.flush();
                response = in.readLine();
                bout.write(response+"\n");
                bout.flush();
                while (!response.contains("OK")) {
                    response = in.readLine();
                    bout.write(response+"\n");
                    bout.flush();
                }
            }
            bout.flush();
        } else {
            out.write(logon);
            out.flush();
            out.write(logon);
            out.flush();
            while (!response.contains("OK")) {
                response = in.readLine();
                bout.write(response+"\n");
                bout.flush();
            }
        }
        bout.flush();
    }
}

我已经找到了Apaches公共池库,但在使用我的MvTelnet类作为池的对象时,我无法弄清楚如何正确实现它。 commons-pool是正确的方法,如果是,我该如何实现呢?

修改 好吧,我在评论中添加了所有代码。我想创建一个各种MvTelnet对象的池,我的套接字可以发送命令。我在bc中没有任何池代码,只是一团糟。

1 个答案:

答案 0 :(得分:0)

如果要创建具有多个连接的客户端 - 服务器,则必须通过连接使用一个线程。当客户端询问连接时,添加一个新线程,该线程将处理新客户端的输入输出。

编辑:如果需要,您可以使用有限数量的线程,只需创建一个向客户端分配新线程的函数,当且仅当有空闲位置时。例如here