Spring Boot 集成 Message

32.Messaging

32.1.JMS(TODO)

 

32.2.amqp(TODO)

 

32.3.Apache Kafka Support (集成kafka)

    32.3.1 Sending a Message

    Spring的KafkaTemplate是自動配置的,你能夠直接在你的bean裏自動裝配,以下示例:html

/**
 * description:kafka 配置文件
 * @author manji
 * @Date 2018年08月21日14:04:45
 */
@Component
public class KafkaConf {
    @Autowired
    private  KafkaTemplate kafkaTemplate;
    /**
     * product message
     * @param topic : topic name
     * @param msg : topic msg
     */
    public void product(String topic, String msg){
        kafkaTemplate.send(topic, msg);
    }
}

 

若是定義了RecordMessageConverter bean,它會自動關聯到自動配置的KafkaTemplate.java

    32.3.2 Receiving a Message

當Apache Kafka 相關引用存在,能夠用@KafkaListener註解在任何bean上面建立監聽端點. 若是不手動定義KafkaListenerContainerFactory的話,默認值經過spring.kafka.listener.* 鍵進行自動配置. 固然,若是自定義了一個RecordMessageConverter bean,它會自動關聯到默認工廠。spring

下面Component 在"manjixx_test" topic上建立一個切點:json

/**
 * description:kafka 配置文件
 * @author manji
 * @Date 2018年08月21日14:04:45
 */
@Component
@Slf4j
public class KafkaConf {
    @Autowired
    private  KafkaTemplate kafkaTemplate;

    @KafkaListener(topics = {"manjixx_test"})
    public String consumer(String message){
        log.info("test topic message : {}" , message    );
        return message;
    }
}

    32.3.3 Additional Kafka Properties

支持自動配置的屬性顯示在 Appendix A, Common application properties. 注意, 大多數狀況下, 這些屬性直接映射Apache Kafka 點狀屬性. 有關詳細信息請查看 Apache Kafka文檔. app

這些屬性中的前幾個同時適用於生產者和消費者,可是若是你想生產者和消費者屬性使用不一樣的值,則能夠在生產者和消費者級別指定. Apache Kafka指定屬性的重要性經過HIGH, MEDIUM, or LOW. Spring Boot 自動配置支持全部HIGH等級重要性的屬性,一些選擇的MEDIUM 和LOW屬性,以及任何沒有默認值的屬性. spring-boot

KafkaProperties類只提供Kafka支持的屬性的子集. 若是你想配置一些額外的不直接支持的屬性在生產者和消費者上,使用如下properties:spa

spring.kafka.properties.prop.one=first
spring.kafka.admin.properties.prop.two=second
spring.kafka.consumer.properties.prop.three=third
spring.kafka.producer.properties.prop.four=fourth

設置的第一個kafka屬性 prop.one 值爲one(適用於 生產者,消費者,管理員), prop.two = second 適用於管理員,prop.three = three 消費者屬性,prop.four = fourth 適用於生產者.code

你也能夠按照以下方式設置kafka 的Json反序列化方式:htm

spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer
spring.kafka.consumer.properties.spring.json.value.default.type=com.example.Invoice
spring.kafka.consumer.properties.spring.json.trusted.packages=com.example,org.acme

一樣的, 你能夠禁用JsonSerializer在頭文件中發送類信息的行爲:three

spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer
spring.kafka.producer.properties.spring.json.add.type.headers=false

TIPS: 以上面這種方式設置的屬性會把Spring Boot 明確支持的配置項覆蓋. 

相關文章
相關標籤/搜索