spring cloud stream操作kafka和redis,以及kafka与redis队列性能比较(未完)

上次用redis队列做了性能测试,不过redis毕竟不是专门用来做队列的,这次用kafka试试。

这次我用spring cloud stream来操作kafka。

Spring Cloud Stream是构建消息驱动的微服务应用程序的框架。Spring Cloud Stream基于Spring Boot构建独立的生产级Spring应用程序,并使用Spring Integration为消息代理提供连接。它提供了来自多个供应商的中间件的自定义配置,介绍了持久发布 - 订阅语义,消费者组和分区的概念。

好了,开始,首先修改pom文件

 



    4.0.0

    com.xzg
    kafka
    1.0-SNAPSHOT
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.1.RELEASE
    
    
        
            
                org.springframework.cloud
                spring-cloud-stream-dependencies
                Fishtown.BUILD-SNAPSHOT
                pom
                import
            
        
    
    
        
            org.springframework.cloud
            spring-cloud-stream
        
        
            org.springframework.cloud
            spring-cloud-starter-stream-kafka
        
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            mysql
            mysql-connector-java
        
    
    
        
            spring-snapshots
            Spring Snapshots
            https://repo.spring.io/libs-snapshot
            
                true
            
        
    

 

等待一会儿,待jar包下载完毕

 

编写启动类Application

 

package com.xzg.kafka;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class Application {
    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
    public static void main(String[] args){
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        LOGGER.info("app started");
    }
}

创建接收消息类

 

package com.xzg.kafka.message;
import com.xzg.kafka.repository.StockRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.stereotype.Component;

@Component
@EnableBinding(Sink.class)
public class Receiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
    @Autowired
    StockRepository stockRepository;
    @StreamListener(Sink.INPUT)
    public void receiveMessage(String message) {
        stockRepository.buy(Long.valueOf(message));
    }
}

 

 

 

 

你可能感兴趣的:(kafka,java)