Spring Cloud Stream与Kafka(二)

Spring Cloud Stream与Kafka(二)

Spring Cloud Stream提供的信道

  1. Source接口
package org.springframework.cloud.stream.messaging;

import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;

//具有一个输出通道的可绑定接口
public interface Source {
    
    //输出通道的名称
    String OUTPUT = "output";
    
    //输出通道
    @Output(Source.OUTPUT)
    MessageChannel output();
}
  1. Sink接口
package org.springframework.cloud.stream.messaging;

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;

//具有一个输入通道的可绑定接口
public interface Sink {
    //输入通道的名称
    String INPUT = "input";
    
    //输入通道
    @Input(Sink.INPUT)
    SubscribableChannel input();
}
  1. Processor接口
package org.springframework.cloud.stream.messaging;

//具有一个输入和一个输出通道的可绑定接口
public interface Processor extends Source, Sink {
    
}

自定义Binding声明接口

  1. 创建自定义绑定接口,定义@Input和@Output时如果没有名称,默认获取当前方法的名称作为绑定名称。应用的时候和其他的绑定接口一样通过@EnableBinding进行声明。
public interface CustomBinding {
    String INPUT1 = "input1";
    String OUTPUT1 = "output1";
    
    @Input
    SubscribableChannel input1();
    
    @Output
    MessageChannel output1();
}
  1. 应用自定义接口
@SpringBootApplication
@EnableBinding({CustomBinding.class, Source.class})
public class Application implements CommandLineRunner{
    
}

Spring Cloud Stream注解

  1. @Output注解指示框架将会创建一个输出绑定目标。
public @interface Output {
    //指定绑定目标名称及绑定目标的Bean名称,以及作为默认的destination名称
    String value() default "";
}
  1. @Input注解指示框架将会创建一个输入绑定目标。
public @interface Input {
	//指定绑定目标名称及绑定目标的Bean名称,以及作为默认的destination名称   
    String value() default "";
}
  1. @StreamListener注解可以把方法标记为通过@EnableBinding注解声明的输入的监听器。
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@MessageMapping
@Documented
public @interface StreamListener {
    //方法订阅的绑定目标的名称比如通道
    @AliasFor("target")
    String value() default "";
    
    @AliasFor("value")
    String target() default "";
    
    //分派给此方法的所有项都必须要满足的条件
    String condition() default "";
    
    //默认是true,当有一个@SendTo注解时,把流入的头信息复制到流出的消息中
    String copyHeaders() default "true";
}
  1. @SendTo注解指示方法的返回值被转换为消息发送到指定的目的地。
public @interface SendTo {
    //从方法的返回值创建的消息的目的地
    String[] value() default {};
}
  1. @EnableBinding根据作为值传递给注释的接口列表,启用带有@Input和@Output注释的目标绑定到代理。
@Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@Import({ BindingBeansRegistrar.class, BinderFactoryConfiguration.class })
@EnableIntegration
public @interface EnableBinding {
    //带有@Input或@Output注解的方法的接口列表表示绑定目标
    Class<?>[] value() default {};
}
package org.springframework.cloud.stream.config;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.binding.BindingBeanDefinitionRegistryUtils;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;

//绑定Bean注册器
public class BindingBeansRegistrar implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata metadata,
			BeanDefinitionRegistry registry) {
		AnnotationAttributes attrs = 
            AnnotatedElementUtils.getMergedAnnotationAttributes(
				ClassUtils.resolveClassName(metadata.getClassName(), null),
				EnableBinding.class);
		for (Class<?> type : collectClasses(attrs, metadata.getClassName())) {
			if (!registry.containsBeanDefinition(type.getName())) {
				BindingBeanDefinitionRegistryUtils
                    .registerBindingTargetBeanDefinitions(
                    	type, type.getName(), registry);
				BindingBeanDefinitionRegistryUtils
					.registerBindingTargetsQualifiedBeanDefinitions(ClassUtils
				.resolveClassName(metadata.getClassName(), null), type,	registry);				}
		}
	}

	private Class<?>[] collectClasses(AnnotationAttributes attrs, String className) {
		EnableBinding enableBinding = AnnotationUtils.synthesizeAnnotation(attrs,
				EnableBinding.class, ClassUtils.resolveClassName(className, null));
		return enableBinding.value();
	}

}

发布与订阅

  1. Spring Cloud Stream默认在接收和发送消息时对应的消息格式类型都是JSON,我们可以通过绑定的contentType属性进行指定。当发送和接收消息时都会被MessageConverter消息转换器进行转换。
spring.cloud.stream.bindings.output.content-type=application/json
# 发布者配置
spring.cloud.stream.bindings.output1.destination=test
# 消费者配置
spring.cloud.stream.bindings.input1.destination=test
spring.cloud.stream.bindings.input1.group=test_group
Spring Cloud Stream是一个基于Spring Boot的框架,用于构建可扩展和可靠的消息驱动型微服务应用程序。而Kafka是一个分布式流媒体平台,用于构建实时数据流应用程序。 在Spring Cloud Stream中集成Kafka非常简单。首先,需要在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream-binder-kafka</artifactId> </dependency> ``` 接下来,需要在项目的application.properties文件中配置Kafka的相关信息,包括Kafka服务器的地址和端口号、Topic的名称等。下面是一个示例配置: ```properties spring.cloud.stream.kafka.binder.brokers=192.168.0.1:9092 spring.cloud.stream.bindings.input.destination=my-topic spring.cloud.stream.bindings.output.destination=my-topic ``` 在上述配置中,`spring.cloud.stream.kafka.binder.brokers`指定Kafka服务器的地址和端口号,`spring.cloud.stream.bindings.input.destination`和`spring.cloud.stream.bindings.output.destination`分别指定了输入和输出的Topic名称。 然后,可以使用`@EnableBinding`注解启用绑定器并定义输入和输出的通道。例如,可以创建一个消费者类并定义一个`@Input`注解,用于接收来自Kafka Topic的消息: ```java @EnableBinding(Processor.class) public class Consumer { @StreamListener(Processor.INPUT) public void receive(String message) { System.out.println("Received message: " + message); } } ``` 类似地,可以创建一个生产者类并定义一个`@Output`注解,用于将消息发送到Kafka Topic: ```java @EnableBinding(Processor.class) public class Producer { @Autowired private MessageChannel output; public void send(String message) { output.send(MessageBuilder.withPayload(message).build()); } } ``` 以上是使用Spring Cloud Stream配置Kafka的基本步骤。通过这种方式,我们可以轻松地实现消息驱动型的微服务应用程序,并且享受到Kafka作为分布式流媒体平台的优势。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐江小鱼

知识创造财富,余额还是小数

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值