Go - helloworld in eclipse


Introduction
When trying the first helloworld, I encountered some problem to setup environment. So note here.
You can find manual for complete information, here is just what I remember work for me.

Install Eclipse & Install Go
skip.. You can execute 
go version
to check is Go installed

Setup Env (Win10)
goroot
You don't need to set it, it was set to installed folder automatically in my machine
Set env: GOROOT={InstalledPath}

gopath
Set to a location for Go workspace
Set env: GOPATH={USERHOME}/Go
Remember to create this folder by yourself, otherwise eclipse may encounter problem

path
Add {Go installation}/bin
Check env

Eclipse
Download tools
Windows -> Preference -> Go -> Tools
Helloworld
Prepare script
This file need to be put under main folder, because it needs to be in main package
package main
import (
       "fmt"
)
func main() {
       fmt.Print("hello world")
}
File structure
Finally you can run the script to get helloworld print result


Spring Integration - Message Flow - Router

Reference

Message Flow
Router - 透過條件判斷要把訊息轉到哪, 也可以轉給多個點
Filter - 透過條件決定要不要把訊息 forward 出去
Splitter - 可以把一個訊息轉成多個訊息
Aggregator - 可以接收多個訊息, 等新訊息被組成完整之後就可以送出
Resequencer - 收到訊息之後重新排列訊息再送出

Router Example
MyMessage 有一個 to 指向要去的 target channel.
MessageRouter 接收到 MyMessage 之後回傳要去的 channel, 所以直接回傳 target channel.
RouterMain.java
public class RouterMain {

    public static void main(String[] params) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:RouterMain.xml");
        MessageChannel input = ctx.getBean("input", MessageChannel.class);

        input.send(MessageBuilder.withPayload(new MyMessage("database", "needPersist")).build());
        input.send(MessageBuilder.withPayload(new MyMessage("memory", "noNeedPersist")).build());


        PollableChannel dbOutput = ctx.getBean("database", PollableChannel.class);
        System.out.println("from DB:" + dbOutput.receive());
        PollableChannel memOutput = ctx.getBean("memory", PollableChannel.class);
        System.out.println("from Memory" + memOutput.receive());
    }
}
MyMessage.java 這裡用了 lombok 減少程式 (lombok 會產生 getter/setter/constructor)
@AllArgsConstructor
@Data
public class MyMessage {

    private String to;
    private String message;

}

MessageRouter.java 收到 MyMessage 之後回傳這個 message 要轉去的 channel
@Component
public class MessageRouter {
    @Router
    public String route(MyMessage msg) {
        System.out.println("msg.to:" + msg.getTo());
        return msg.getTo();
    }
}
RouterMain.xml
定義了 input channel 的訊息會被 messageRouter 導向其他 channel.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration-5.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="examples.router"/>

    <int:router input-channel="input" ref="messageRouter" />

    <int:channel id="input"/>
    <int:channel id="database">
        <int:queue capacity="10"/>
    </int:channel>
    <int:channel id="memory">
        <int:queue capacity="10"/>
    </int:channel>
    <int:channel id="output">
        <int:queue capacity="10"/>
    </int:channel>
</beans>






Spring Integration - Header Enricher

Reference

Enrich Header XML
  1. Header-enricher 可以改變 msg 的 header, 這裡把 mykey 加入 message
  2. Transformer 可以透過 @Header 或 @Headers 來取得 headers
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration-5.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="examples"/>
    <int:header-enricher input-channel="input" output-channel="inteceptor">
        <int:header name="mykey" value="myval" />
    </int:header-enricher>

    <int:transformer input-channel="inteceptor" output-channel="output" ref="mapper" />


    <int:channel id="inteceptor" />
    <int:channel id="input"/>
    <int:channel id="output">
        <int:queue capacity="10"/>
    </int:channel>
</beans>

HeaderEnricherMain
public class HeaderEnricherMain {

    public static void main(String[] params) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:HeaderEnricherMain.xml");
        MessageChannel input = ctx.getBean("input", MessageChannel.class);
        input.send(MessageBuilder.withPayload("test").build());


        PollableChannel output = ctx.getBean("output", PollableChannel.class);
        System.out.println(output.receive().getHeaders().get("mykey")); // print myval
    }

}


Transformer 用 @Header or @Headers 取值
@Component
public class Mapper {

    @Transformer
    public TextMessage map(Map<String, String> message) {
        System.out.println("transform from " + message + " to TextMessage");
        return new TextMessage(message.get("text"));
    }

    @Transformer
    public TextMessage map(String message) {
        System.out.println("transform from string to TextMessage");
        return new TextMessage(message);
    }

    @Transformer
    public TextMessage mapMyKey(@Header("mykey") String myval, @Headers Map<String,String> headerMap, String message) {
        System.out.println("headerMap:" + headerMap);
        return new TextMessage(myval); // myval
    }

}




Spring Integration - Integrate with ActiveMQ

Reference

ActiveMQ Example
這是個純粹的 ActiveMQ + JMS API 範例
public class ActiveMQMain {

    public static void main(String[] params) throws Exception {
        ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
        Connection connection = getConnection(factory);
        connection.start();
        System.out.println("create session");
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination dst = session.createQueue("test");

        System.out.println("create producer");
        MessageProducer producer = session.createProducer(dst);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        TextMessage msg = session.createTextMessage("my test msg");

        System.out.println("send message");
        producer.send(msg);

        MessageConsumer consumer = session.createConsumer(dst);
        System.out.println("consume message");
        System.out.println(consumer.receive());

        System.out.println("close session");
        session.close();
        System.out.println("close connection");
        connection.close();
        System.out.println("done");
    }

    private static Connection getConnection(ConnectionFactory factory) {
        Connection result = null;
        while (result == null) {
            try {
                result = factory.createConnection();
                System.out.println("connection get!");
            } catch (Exception ex) {
                System.err.println(ex);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    private static void asyncStart(BrokerService brokerService) {
        new Thread(() -> {
            try {
                brokerService.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

}



JmsTemplate Example
用 JmsTemplate 來傳送與接收訊息
public class JmsTemplateMain {

    public static void main(String[] params) throws JMSException {
        ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
        JmsTemplate template = new JmsTemplate(factory);
        template.setDefaultDestinationName("test");
        template.send(session -> {
            MapMessage msg = session.createMapMessage();
            msg.setString("text", UUID.randomUUID().toString());
            return msg;
        });
        MapMessage msg = (MapMessage) template.receive();
        System.out.println("receive msg:" + msg.getString("text"));
    }


    private static Connection getConnection(ConnectionFactory factory) {
        Connection result = null;
        while (result == null) {
            try {
                result = factory.createConnection();
                System.out.println("connection get!");
            } catch (Exception ex) {
                System.err.println(ex);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}


Integrate with ActiveMQ Example
Maven Dependency
首先, maven dependency 很關鍵, 以下是我做範例時候使用到相關的 dependency
<dependency>
   <groupId>org.springframework.integration</groupId>
   <artifactId>spring-integration-core</artifactId>
   <version>5.0.3.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jms</artifactId>
   <version>5.0.3.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework.integration</groupId>
   <artifactId>spring-integration-jms</artifactId>
   <version>5.0.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.15.3</version>
</dependency>
<dependency>
    <groupId>javax.jms</groupId>
    <artifactId>javax.jms-api</artifactId>
    <version>2.0.1</version>
</dependency>

Main Class
這裡是用 JmsTemplate 向 Spring Integration 的 queue 送訊息, 預期這個訊息會被轉到 output channel.
再用 PollableChannel 取資料
public class IntegrateActiveMQMain {

    public static void main(String[] params) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:IntegrateActiveMQMain.xml");
        JmsTemplate jmsTemplate = ctx.getBean("jmsTemplate", JmsTemplate.class);
        jmsTemplate.send(session -> {
            MapMessage msg = session.createMapMessage();
            msg.setString("text", UUID.randomUUID().toString());
            return msg;
        });

        PollableChannel output = ctx.getBean("output", PollableChannel.class);
        Message<?> reply = output.receive();
        System.out.println("received: " + reply.getPayload());

        ctx.close();
    }

}

IntegrateActiveMQMain.xml
  1. 設定 connectionFactory, 讓 jms client 發送訊息, 也準備讓接收端拿到 connection. 實際上這兩個角色可能是在不同的 process.
  2. 用 message-driven-channel-adapter 去連接 MQ.
  3. 用 transformer 轉換收到的訊息, 目前支援 map message, transformer 會把轉換後的訊息丟給 output channel.
  4. Transformer 是把 map message 轉為 TextMessageEmptyConstructor
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:jms="http://www.springframework.org/schema/integration/jms"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration-5.0.xsd
        http://www.springframework.org/schema/integration/jms
        http://www.springframework.org/schema/integration/jms/spring-integration-jms-5.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="examples"/>

    <bean id="cachingConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <constructor-arg value="vm://localhost" />
    </bean>

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <constructor-arg ref="cachingConnectionFactory" />
        <property name="defaultDestinationName" value="transformation.example.queue" />
    </bean>

    <jms:message-driven-channel-adapter
            channel="map"
            connection-factory="cachingConnectionFactory"
            destination-name="transformation.example.queue"/>

    <int:map-to-object-transformer input-channel="map" output-channel="output"
                                   type="examples.transformer.TextMessageEmptyConstructor" />

    <int:channel id="map" />
    <int:channel id="output">
        <int:queue capacity="10"/>
    </int:channel>
</beans>



TextMessageEmptyConstructor
public class TextMessageEmptyConstructor {

    private String text;

    public TextMessageEmptyConstructor() {}
    public TextMessageEmptyConstructor(String text) {
        this.text = text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "=>" + text;
    }
}




難開的瓶蓋

家裡最近買一個洗髮精, 讓我洗得很痛苦.

讓我痛苦的點是瓶蓋, 瓶蓋如下圖.

















這個瓶蓋的問題在: 洗澡的時候很難知道要從哪邊開.
這個圓形的瓶蓋, 只有一個凹槽可以把瓶蓋打開, 但那個凹槽 (右邊那張圖) 不明顯.

覺得應該是因為整個洗髮精都是黃色的, 為了一致性所以瓶蓋也需要是黃色的吧?
顏色的部分可能無法改變, 但如果可以改成像寶特瓶那樣用轉的就可以很好用了.
 好用的原因是: 這種瓶蓋的使用方式很明確, 可以跟顏色無關.
如果設計的條件是顏色要黃色, 這種瓶蓋可以避免被顏色干擾.

可能是會被詬病比較醜吧?

Spring Integration - Transformations



Reference

Transformer 用來轉換收進來的訊息
Example 把 Map 或 String 改為 TextMessage. Mapper 掛上 @Transformer 就是註冊 Transformer, 根據 parameter type 可以自動判斷哪個 transformer method 要被呼叫
// Mapper
@Component
public class Mapper {

    @Transformer
    public TextMessage map(Map<String, String> message) {
        System.out.println("transform from " + message + " to TextMessage");
        return new TextMessage(message.get("text"));
    }

    @Transformer
    public TextMessage map(String message) {
        System.out.println("transform from string to TextMessage");
        return new TextMessage(message);
    }

}

// TextMessage
public class TextMessage {

    private final String text;

    public TextMessage(String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        return text;
    }
}

// TransformerMain.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration-5.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="examples.transformer"/>
    <int:transformer input-channel="input"
                     output-channel="output"
                     ref="mapper"/>
    <int:channel id="input"/>
    <int:channel id="output">
        <int:queue capacity="10"/>
    </int:channel>
</beans>

// TransformerMain.java
public class TransformerMain {

    public static void main(String[] params) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:TransformerMain.xml");
        MessageChannel input = ctx.getBean("input", MessageChannel.class);
        PollableChannel output = ctx.getBean("output", PollableChannel.class);
        Map<String,String> message = new HashMap<>();
        message.put("text", "here");
        input.send(MessageBuilder.withPayload(message).build());
        System.out.println(output.receive().getPayload());


        input.send(MessageBuilder.withPayload("fromString").build());
        System.out.println(output.receive().getPayload());
    }

}


Object-to-string transformer
Example 不用設定 mapper 就會呼叫 toString 轉換
// ObjectToStringTransformer.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration-5.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="examples.transformer"/>
    <int:object-to-string-transformer input-channel="input" output-channel="output" />
    <int:channel id="input"/>
    <int:channel id="output">
        <int:queue capacity="10"/>
    </int:channel>
</beans>

public class ObjectToStringTransformerMain {

    public static void main(String[] params) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:ObjectToStringTransformerMain.xml");
        MessageChannel input = ctx.getBean("input", MessageChannel.class);
        PollableChannel output = ctx.getBean("output", PollableChannel.class);
        Map<String,String> message = new HashMap<>();
        message.put("text", "here");
        input.send(MessageBuilder.withPayload(message).build());
        System.out.println(output.receive().getPayload());


        input.send(MessageBuilder.withPayload("fromString").build());
        System.out.println(output.receive().getPayload());
    }

}

Payload-serializer-transformer 對 payload 直接做 serialize/deserialize
Example localId in TextMessage 是 transient, 所以不會被 serialize/deserialize
// XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration-5.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="examples.transformer"/>
    <int:payload-serializing-transformer input-channel="input" output-channel="byte-array" />
    <int:payload-deserializing-transformer input-channel="byte-array" output-channel="output" />
    <int:channel id="byte-array" />
    <int:channel id="input"/>
    <int:channel id="output">
        <int:queue capacity="10"/>
    </int:channel>
</beans>


public class TextMessage implements Serializable {

    private final String text;
    private final transient String localId;

    public TextMessage(String text) {
        this(text, UUID.randomUUID().toString());
    }

    public TextMessage(String text, String localId) {
        this.text = text;
        this.localId = localId;
    }

    @Override
    public String toString() {
        return localId + ":" + text;
    }
}

public class PayloadSerializingTransformerMain {

    public static void main(String[] params) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:PayloadSerializingTransformerMain.xml");
        MessageChannel input = ctx.getBean("input", MessageChannel.class);
        PollableChannel output = ctx.getBean("output", PollableChannel.class);
        TextMessage message = new TextMessage("testa", "1");

        input.send(MessageBuilder.withPayload(message).build());
        System.out.println(output.receive().getPayload()); // localId will become null
    }

}



Map-to-object transformer 替 payload 做 marshal/unmarshal to map
Example 這裡要注意的是 訊息必須有空的建構子與 setter/getter, 不然會失敗
// XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration-5.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="examples.transformer"/>
    <int:object-to-map-transformer input-channel="input" output-channel="map" />
    <int:map-to-object-transformer input-channel="map" output-channel="output" type="examples.transformer.TextMessageEmptyConstructor" />
    <int:channel id="map" />
    <int:channel id="input"/>
    <int:channel id="output">
        <int:queue capacity="10"/>
    </int:channel>
</beans>

// Payload class
public class TextMessageEmptyConstructor {

    private String text;

    public TextMessageEmptyConstructor() {}
    public TextMessageEmptyConstructor(String text) {
        this.text = text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return text;
    }
}

// Transformer
public class MapToObjectTransformerMain {

    public static void main(String[] params) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:MapToObjectTransformerMain.xml");
        MessageChannel input = ctx.getBean("input", MessageChannel.class);
        PollableChannel output = ctx.getBean("output", PollableChannel.class);

        TextMessageEmptyConstructor message = new TextMessageEmptyConstructor("testa");

        input.send(MessageBuilder.withPayload(message).build());
        System.out.println(output.receive().getPayload()); // localId will become null
    }

}


Object-to-json transformer payload 會轉成 json 再轉回 payload 物件
Example
// XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration-5.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="examples.transformer"/>
    <int:object-to-json-transformer input-channel="input" output-channel="json" />
    <int:json-to-object-transformer input-channel="json" output-channel="output" type="examples.transformer.TextMessageEmptyConstructor" />

    <int:channel id="json" />
    <int:channel id="input"/>
    <int:channel id="output">
        <int:queue capacity="10"/>
    </int:channel>
</beans>

// transformer
public class ObjectToJsonTransformerMain {

    public static void main(String[] params) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:ObjectToJsonTransformerMain.xml");
        MessageChannel input = ctx.getBean("input", MessageChannel.class);
        PollableChannel output = ctx.getBean("output", PollableChannel.class);

        TextMessageEmptyConstructor message = new TextMessageEmptyConstructor("test-object-to-json");

        input.send(MessageBuilder.withPayload(message).build());
        System.out.println(output.receive().getPayload());
    }

}



Spring Integration - Channels


Reference

Concept
  • Point to Point Channel - 保證只有一個 receiver 會收到訊息. Ex. QueueChannel, PriorityChannel, RendezvousChannel, DirectChannel, ExecutorChannel, and NullChannel.
  • Publish-Subscribe Channel - 訊息會被多個 receiver 收到
  • Data-Typed Channel - receiver 透過 data type 來決定是否要收訊息, 這種 channel, receiver 需要知道自己要處理的 data type 是什麼.
  • Invalid Message Channel - application 決定某個 message 無效之後可以把 message 丟到這個 channel 來讓別的 application 決定怎麼處理無用的 message
  • Dead Letter Channel - producer 重複送訊息失敗幾次後就會把訊息送到 Dead Letter Channel 給其他 application 處理
  • Channel Adapter - 用來跟 message system 對接
  • Message Bridge - 用來連接兩個 channel 或 channel adapter
  • Message Bus - 透過一致的 API 讓不同系統進行訊息溝通
  • Guaranteed Delivery - 預設 Spring Integration 把 message 存在記憶體中, Spring Integration 2.0 後支援外部 message broker, 讓保證送達的功能由外部 message system 提供
Channels
MessageChannel
用來送訊息
public interface MessageChannel {
  boolean send(Message<?> message);
  boolean send(Message<?> message, long timeout);
}

PollableChannel
是 MessageChannel 的一種實作, 可以送訊息.
另外 PollableChannel 則是定義可以收訊息.
public interface PollableChannel extends MessageChannel {
  Message<?> receive();
  Message<?> receive(long timeout);
}
SubscribableChannel
是 MessageChannel 的一種實作, 可以傳送訊息.
另外 SubscribableChannel 還定義 MessageHandler 讓 API Client 能註冊自己的 MessageHandler 接收每一個訊息.
public interface MessageHandler {
  void handleMessage(Message<?> message) throws MessageException;
}

public interface SubscribableChannel extends MessageChannel {
  boolean subscribe(MessageHandler handler);
  boolean unsubscribe(MessageHandler handler);
}
QueueChannel
是一種 Point to Point Channel. 能保證只有一個 consumer 會收到訊息.
Example 每個 receiver 都在 receive, 但每個訊息都只會被一個 receiver 收走.
public class QueueChannelMain {

    static final Map<Object, AtomicInteger> receiveMsgCount = new ConcurrentHashMap<>();
    static final CountDownLatch l = new CountDownLatch(10);

    public static void main(String[] params) throws InterruptedException {
        QueueChannel channel = new QueueChannel();
        new Receiver(channel).start();
        new Receiver(channel).start();
        new Receiver(channel).start();
        LongStream.range(0,l.getCount()).forEach(idx -> {
            String msg = "Message" + idx;
            System.out.println("send msg:" + msg);
            channel.send(MessageBuilder.withPayload(msg).build());
        });
        l.await();
        System.out.println("test done. receiveMsgCount:" + receiveMsgCount);
    }

    public static class Receiver extends Thread {
        private QueueChannel channel;

        Receiver(QueueChannel channel) {
            this.channel = channel;
        }

        @Override
        public void run() {
            while (l.getCount() != 0) {
                Message m = channel.receive(TimeUnit.SECONDS.toMillis(1));
                if (m == null) {
                    continue;
                }
                Object pl = m.getPayload();
                receiveMsgCount.putIfAbsent(pl, new AtomicInteger());
                receiveMsgCount.get(pl).incrementAndGet();
                System.out.println(Thread.currentThread().getName() + " got message: " + pl + ", count:" + l);
                l.countDown();
            }
        }
    }

}
Example QueueChannel 是 FIFO, 如果超過 capacity, sender 會被 block.
public class QueueChannelMainExceedCapacityMain {

    public static void main(String[] params) {
        QueueChannel channel = new QueueChannel(2);
        send(channel, "1");
        send(channel, "2");
        send(channel, "3");
        System.out.println(channel.receive(1000));
        System.out.println(channel.receive(1000));
        System.out.println(channel.receive(1000));
    }

    private static void send(QueueChannel channel, String s) {
        try {
            System.out.println("send:" + s);
            channel.send(MessageBuilder.withPayload(s).build(), 1000); // the third message won't be sent
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}



PriorityChannel 支援訊息進 channel 之後可以排隊
Example 預設會用 Message 的 header 的 PRIORITY
public class DefaultPriorityChannelMain {

    public static void main(String[] params) throws InterruptedException {
        PriorityChannel channel = new PriorityChannel();
        channel.send(MessageBuilder.withPayload("MSG1").setPriority(1).build());
        channel.send(MessageBuilder.withPayload("MSG2").setPriority(2).build());
        channel.send(MessageBuilder.withPayload("MSG3").setPriority(3).build());
        System.out.println(channel.receive()); // priority:3
        System.out.println(channel.receive()); // priority:2
        System.out.println(channel.receive()); // priority:1
    }

}
Example 可以指定自己的 Comparator
public class PriorityChannelCustomComparatorMain {

    public static void main(String[] params) {
        PriorityChannel channel = new PriorityChannel(Comparator.comparingLong(m -> (Long) m.getHeaders().get("MYVAL")));
        channel.send(MessageBuilder.withPayload("MSG1").setHeader("MYVAL", 3L).build());
        channel.send(MessageBuilder.withPayload("MSG2").setHeader("MYVAL", 2L).build());
        channel.send(MessageBuilder.withPayload("MSG3").setHeader("MYVAL", 1L).build());
        System.out.println(channel.receive()); // MYVAL:1
        System.out.println(channel.receive()); // MYVAL:2
        System.out.println(channel.receive()); // MYVAL:3
    }

}
RendezvousChannel synchronized QueueChannel, 內部 Queue 實作是 SynchronousQueue
Example 等到有人在等待訊息來, 不然會送不出去
public class RendezvousChannelMain {

    public static void main(String[] params) {
        RendezvousChannel channel = new RendezvousChannel();
        receive(channel);
        System.out.println("send 1");
        channel.send(MessageBuilder.withPayload("MSG1").build());
        System.out.println("send 2 and block until message was received");
        channel.send(MessageBuilder.withPayload("MSG2").build());
        System.out.println("won't reach here");
    }

    private static void receive(QueueChannel channel) {
        new Thread(() -> System.out.println("receive:" + channel.receive())).start();
    }

}

DirectChannel 提供 Pub-Sub 的 interface, 用 MessageHandler 收訊息, 但像 QueueChannel 一樣只會有一個 MessageHandler 收到.
Example
public class DirectChannelMain {

    public static void main(String[] params) {
        DirectChannel channel = new DirectChannel();
        channel.subscribe(new MyMessageHandler(1));
        channel.subscribe(new MyMessageHandler(2));
        channel.subscribe(new MyMessageHandler(3));
        channel.send(MessageBuilder.withPayload("MSG1").build());
        channel.send(MessageBuilder.withPayload("MSG2").build());
        channel.send(MessageBuilder.withPayload("MSG3").build());
    }

    static class MyMessageHandler implements MessageHandler {

        private final int id;

        MyMessageHandler(int id) {
            this.id = id;
        }

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            System.out.println("handler " + id + " receive:" + message);
        }
    }
}

ExecutorChannel 跟 DirectChannel 一樣, 但可以提供 Executor, 所以 sender 不會被 block
Example
public class ExecutorChannelMain {
    public static void main(String[] params) {
        ExecutorChannel channel = new ExecutorChannel(Executors.newCachedThreadPool());
        channel.subscribe(new MyMessageHandler(1));
        channel.subscribe(new MyMessageHandler(2));
        channel.subscribe(new MyMessageHandler(3));
        channel.send(MessageBuilder.withPayload("MSG1").build());
        channel.send(MessageBuilder.withPayload("MSG2").build());
        channel.send(MessageBuilder.withPayload("MSG3").build());
    }

    static class MyMessageHandler implements MessageHandler {

        private final int id;

        MyMessageHandler(int id) {
            this.id = id;
        }

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            System.out.println("handler " + id + " receive:" + message);
        }
    }
}

NullChannel send 的時候永遠說成功但其實不會送, receive 的時候永遠得到 null
Publish-Subscribe Channel 一個訊息送出去, 每個 MessageHandler 都會收到訊息
Example
public class PubsubChannelMain {

    public static void main(String[] params) {
        PublishSubscribeChannel channel = new PublishSubscribeChannel();
        channel.subscribe(new MyMessageHandler(1));
        channel.subscribe(new MyMessageHandler(2));
        channel.subscribe(new MyMessageHandler(3));
        channel.send(MessageBuilder.withPayload("MSG1").build());
        channel.send(MessageBuilder.withPayload("MSG2").build());
        channel.send(MessageBuilder.withPayload("MSG3").build());
    }

    static class MyMessageHandler implements MessageHandler {

        private final int id;

        MyMessageHandler(int id) {
            this.id = id;
        }

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            System.out.println("handler " + id + " receive:" + message);
        }
    }

}
Channel Inteceptors 可以攔截送出或接收到的訊息
Example
public class MessageInteceptorMain {

    public static void main(String[] params) {
        QueueChannel channel = new QueueChannel();
        channel.addInterceptor(new ChannelInterceptor() {
            @Override
            public boolean preReceive(MessageChannel channel) {
                System.out.println("pre receive");
                return true;
            }

            @Override
            public Message<?> postReceive(Message<?> message, MessageChannel channel) {
                System.out.println("post receive:" + message);
                return message;
            }

            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                System.out.println("presend:" + message);
                return message;
            }

            @Override
            public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
                System.out.println("post sned:" + message);
            }
        });
        channel.send(MessageBuilder.withPayload("test").build());
        System.out.println("receive:" + channel.receive());
    }

}

MessageTemplate 提供一些基本操作例如 sendAndReceive
Example sendAndReceive
public class MessagingTemplateMain {

    public static void main(String[] params) {
        QueueChannel channel = new QueueChannel();
        MessagingTemplate template = new MessagingTemplate(channel);
        new Thread(() -> {
            Message<?> message = channel.receive();
            System.out.println("receive:" + message);
            MessageChannel c = (MessageChannel) message.getHeaders().getReplyChannel();
            c.send(MessageBuilder.withPayload("OK!").build());
        }).start();
        template.setReceiveTimeout(10000);
        System.out.println("send and receive:" + template.sendAndReceive(MessageBuilder.withPayload("test").build()));

    }

}


Lessons Learned While Benchmarking vLLM with GPU

Recently, I benchmarked vLLM on a GPU to better understand how much throughput can realistically be expected in an LLM serving setup. One ...