方案一:同步调用
缺点:1.业务耦合
2.降低整体性能
3.当一个业务出现问题则直接卡死
方案二:异步通知(解除了两个服务之间的耦合)
缺点:比较依赖与mq
方案三:监听MySQL的binlog日志
三种方式优缺点对比
方案二:
1.引入依赖
<!-- amqp-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.编写配置文件
spring:
rabbitmq:
host: 192.168.2.182
port: 5672
username: root
password: root
virtual-host: /
3.编写名称的常量
public class MqConstants {
/**
* 交换机
*/
public final static String HOTEl_EXCHANGE= "hotel.topic";
/**
* 监听新增和修改的队列
*/
public final static String HOTEl_INSERT_QUEUE= "hotel.insert.queue";
/**
* 监听删除队列
*/
public final static String HOTEl_DELETE_QUEUE= "hotel.delete.queue";
/**
* 新增或修改的Routingkey
*/
public final static String HOTEl_INsERT_KEY= "hotel.topic";
/**
* 删除的Routingkey
*/
public final static String HOTEl_DELETE_KEY = "hotel.delete";
}
4.编写配置类创建队列与交换机并绑定
@Configuration
public class MqConfig {
//创建交换机
@Bean
public TopicExchange topicExchange(){
return new TopicExchange(MqConstants.HOTEl_EXCHANGE,true,false);
}
//创建队列
@Bean
public Queue insertQueue(){
return new Queue(MqConstants.HOTEl_INSERT_QUEUE,true);
}
@Bean
public Queue deleteQueue(){
return new Queue(MqConstants.HOTEl_DELETE_QUEUE,true);
}
@Bean
//绑定交换机与队列
public Binding insertQueueBinding(){
return BindingBuilder.bind(insertQueue()).to(topicExchange()).with(MqConstants.HOTEl_INsERT_KEY);
}
@Bean
//绑定交换机与队列
public Binding deleteQueueBinding(){
return BindingBuilder.bind(deleteQueue()).to(topicExchange()).with(MqConstants.HOTEl_DELETE_KEY);
}
}
5.在发送消息的一方引入依赖和yaml中的配置
6.修改发送一方的业务
@PutMapping()
public void updateById(@RequestBody Hotel hotel){
if (hotel.getId() == null) {
throw new InvalidParameterException("id不能为空");
}
hotelService.updateById(hotel);
//发送消息队列
rabbitTemplate.convertAndSend(MqConstants.HOTEl_EXCHANGE,MqConstants.HOTEl_INsERT_KEY,hotel.getId());
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") Long id) {
hotelService.removeById(id);
//发送消息队列
rabbitTemplate.convertAndSend(MqConstants.HOTEl_EXCHANGE,MqConstants.HOTEl_DELETE_KEY,id);
}
7.在接收一方编写监听器文章来源:https://www.toymoban.com/news/detail-416707.html
@Component
public class HotelListener {
@Autowired
private IHotelService hotelService;
/**
* 监听酒店新增或修改的业务
* @param id 酒店id
*/
@RabbitListener(queues = MqConstants.HOTEl_INSERT_QUEUE)
public void listenHotelInsertOrUpdate(Long id){
hotelService.inter(id);
}
/**
* 监听酒店删除的业务
* @param id 酒店id
*/
@RabbitListener(queues = MqConstants.HOTEl_DELETE_QUEUE)
public void listenHotelDelete(Long id){
hotelService.deleteByid(id);
}
}
重启服务即可实现数据同步
文章来源地址https://www.toymoban.com/news/detail-416707.html
到了这里,关于es与mysql的数据同步问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!