kafka和springboot以及如何使用事务
- 1、引入依赖
<dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>2.2.4.RELEASE</version> </dependency>
 //这个是kafka的<dependency> 
 <groupId>org.slf4j</groupId>
 <artifactId>log4j-over-slf4j</artifactId>
 </dependency>
 //这个是slf4j的
- 2、配置文件:
server: port: 9001 servlet: context-path: /kafka spring: kafka: producer: bootstrap-servers: 10.203.103.66:9092 //生产者的 consumer: 
 bootstrap-servers: 10.203.103.66:9092 //这个是消费者的
 logging:
 level:
 root: INFO
 //红色的是kafka的配置,蓝色的是本地的地址
- 3、消息的发送和消息的监听
@RestController @RequestMapping("kafka") public class KafkaController { @Autowired private KafkaTemplate template; private static final String topic="heima";//设置主题topic private static final Logger LOGGER=LoggerFactory.getLogger(KafkaApplication.class); @RequestMapping("index") public String index(){ return "hello,kafka"; } /* * * 消息的生产者 * */ @GetMapping("/send/{input}") public String sendToKafka(@PathVariable String input){ this.template.send(topic,input); return "send success!"+input; } //这里懒得可以保证把input传进来 /* * 消息的接收 * */ @KafkaListener(id="myContainer1",topics = topic,groupId = "groud.demo-2") public void listener(String input){ LOGGER.info(input); } 如何使用事务控制回滚(已经发了一个消息,但是后面的消息出错了,然后全部回滚) 
- 事务的支持:
spring: kafka: producer: bootstrap-servers: 10.203.103.66:9092 transaction-id-prefix: kafka_tx. consumer: bootstrap-servers: 10.203.103.66:9092 
 //标红的是事务的支持
- 代码部分:控制事务的方式
//编码方式 @GetMapping("/send/{input}") public String sendToKafka(@PathVariable String input){ // this.template.send(topic,input); //事务的支持 template.executeInTransaction(t->{ t.send(topic,input); if("error".equals(input)) { throw new RuntimeException("input is error"); } t.send(topic,input+"anthor"); return true; }); return "send success!"+input; } //第二种 (注解方式) @GetMapping("/send2/{input}") @Transactional(rollbackFor = RuntimeException.class) public String sendToKafka2(@PathVariable String input){ // this.template.send(topic,input); //事务的支持 template.send(topic,input); if("error".equals(input)) { throw new RuntimeException("input is error"); } template.send(topic,input+"anthor"); return "send success!"+input; } 
    along
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号