消息处理中心:
public class Broker { // 最大存储数 private final static int MAX_SIZE = 3; // 保存消息的容器 private static ArrayBlockingQueue<String> messageQueue = new ArrayBlockingQueue<>(MAX_SIZE); // 生产消息 public static void produce(String msg) { if (messageQueue.offer(msg)) { System.out.println("成功向消息中心发消息:" + msg + ",当前容量为:" + messageQueue.size()); } else { System.out.println("消息中心超负荷"); } System.out.println("-----------------"); } // 消费消息 public static String comsume() { String msg = messageQueue.poll(); if (msg != null) { System.out.println("得到消息:" + msg + ",当前容量为:" + messageQueue.size()); } else { System.out.println("消息中心没有消息"); } System.out.println("-----------------"); return msg; } }
服务暴露:
public class BrokerServer implements Runnable { public static int SERVICE_PORT = 9999; private final Socket socket; public BrokerServer(Socket socket) { this.socket = socket; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream())) { while (true) { String str = in.readLine(); if (str == null) { continue; } System.out.println("收到消息为:" + str); if (str.equals("CONSUME")) { // 消费消息 String message = Broker.comsume(); out.println(message); out.flush(); } else { // 生产消息 Broker.produce(str); } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { ServerSocket sever = new ServerSocket(SERVICE_PORT); while (true) { BrokerServer brokerServer = new BrokerServer(sever.accept()); new Thread(brokerServer).start(); } } }
自定义客户端:
public class MyClient { // 生产消息 public static void produce(String message) throws Exception { Socket socket = new Socket(InetAddress.getLocalHost(), BrokerServer.SERVICE_PORT); try (PrintWriter out = new PrintWriter(socket.getOutputStream())) { out.println(message); out.flush(); } } // 消费消息 public static String consume() throws Exception { Socket socket = new Socket(InetAddress.getLocalHost(), BrokerServer.SERVICE_PORT); try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream())) { out.println("CONSUME"); out.flush(); String message = in.readLine(); return message; } } }
生产者客户端:
public class ProduceClient { public static void main(String[] args) throws Exception { MyClient client = new MyClient(); client.produce("hello world"); } }
消费者客户端:
public class ConsumeClient { public static void main(String[] args) throws Exception { MyClient client = new MyClient(); String message = client.consume(); System.out.println("获取消息为:" + message); } }
来源:https://www.cnblogs.com/s-star/p/12050708.html