es与mysql的数据同步问题
方案一:同步调用
缺点: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.182port: 5672username: rootpassword: rootvirtual-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 {//创建交换机@Beanpublic TopicExchange topicExchange(){return new TopicExchange(MqConstants.HOTEl_EXCHANGE,true,false);}//创建队列@Beanpublic Queue insertQueue(){return new Queue(MqConstants.HOTEl_INSERT_QUEUE,true);}@Beanpublic 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.在接收一方编写监听器
@Component
public class HotelListener {@Autowiredprivate 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);}
}
重启服务即可实现数据同步