Подписка на WebSocket с использованием Spring Boot и ReactJsJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Подписка на WebSocket с использованием Spring Boot и ReactJs

Сообщение Anonymous »


Всем доброго дня!

Пожалуйста, я работаю над проектом, который требует, чтобы пользователь запросил транспортное средство, а затем подтвердил запрос. После подтверждения служба весенней загрузки найдет ближайшего водителя и ответит через WebSocket, сообщая водителю пользователя, что его запрос принят или что ни один водитель не нашел.

Я могу подключиться к серверу из Reactjs, однако, если служба весенней загрузки публикует какое-либо сообщение, я могу его получить.

Пожалуйста, помогите

Верхний код
@Configuration @EnableWebSocketMessageBroker @CrossOrigin(origins = "*") публичный класс WebSocketConfig реализует WebSocketMessageBrokerConfigurer { @Override общественный недействительный RegisterStompEndpoints (реестр StompEndpointRegistry) { реестр.addEndpoint("/massitec").setAllowedOrigins("*"); реестр.addEndpoint("/massitec").setAllowedOrigins("*").withSockJS(); } @Override public void configureMessageBroker (конфигурация MessageBrokerRegistry) { config.enableSimpleBroker("/topic", "/queue"); config.setApplicationDestinationPrefixes("/ws"); } } Контроллер @PostMapping("принять") public ResponseEntity AcceptCustomerVehicleRequest(@RequestBody @Valid CustomerVehicleAcceptRequestDto customerVehicleAcceptRequestDto, @RequestHeader("Авторизация") String authToken){ return ResponseEntity.ok(customerVehicleRequestService.acceptCustomerVehicleRequest(customerVehicleAcceptRequestDto,authToken)); } Услуга @Override public MessageResponseDto AcceptCustomerVehicleRequest (CustomerVehicleAcceptRequestDto customerVehicleAcceptRequestDto, String authToken) { if(!customerVehicleAcceptRequestDto.isAccepted()){ вернуть MessageResponseDto.builder() .message("запрос был отклонен вами") .status("успех") .строить(); } Клиент пользователя = аутентификацияService.getUserFromToken(authToken); CustomerTrip customerTrip = CustomerTrip.builder() .vehicleType(customerVehicleAcceptRequestDto.getVehicleType()) .capacity(customerVehicleAcceptRequestDto.getCapacity()) .destinationCoordinate(customerVehicleAcceptRequestDto.getDestinationCoordinate()) .originCoordinate(customerVehicleAcceptRequestDto.getOriginCoordinate()) .destinationLocationName(customerVehicleAcceptRequestDto.getDestinationLocationName()) .originLocationName(customerVehicleAcceptRequestDto.getOriginLocationName()) .клиент(клиент) .distance(customerVehicleAcceptRequestDto.getDistanceInMetres()) .price(customerVehicleAcceptRequestDto.getPrice()) .typeOfGoodsTransported(customerVehicleAcceptRequestDto.getTypeOfGoodsTransported()) .строить(); customerTripRepository.save(customerTrip); findDriverBackgroundService.findDriverForCustomerRequest(customerTrip); вернуть MessageResponseDto.builder() .message("поиск водителя, вы будете уведомлены, когда водитель примет ваш запрос") .status("успех") .строить(); } Служба вебсокетов @Override public void findDriverForCustomerRequest (CustomerTrip customerTrip) { executorService.execute(()->{ Список треки = trackRepository .findAllByVehicle_EVehicleTypeAndVehicle_TypeOfGoodsTransportedAndVehicle_EVehicleStatusAndVehicle_CapacityGreaterThanEqualAndVehicle_DriverAvailability_AvailableIsTrueAndVehicle_DriverUserIsNotNull( customerTrip.getVehicleType(),customerTrip.getTypeOfGoodsTransported(), EVehicleStatus.ACTIVE, customerTrip.getCapacity()); Отследить ближайшийTrack = DistanceCalculator.findClosestCoordinate(tracks, customerTrip.getOriginCoordinate()); если (closestTrack == ноль) { log.error("Драйвер не найден по запросу клиента: {}", customerTrip); simpMessagingTemplate.convertAndSendToUser(customerTrip.getCustomer().getEmailAddress(), "/topic/customer-trip", MessageResponseDto.builder() .status("не удалось") .message("Драйвер по вашему запросу не найден") .строить()); throw new NotFound404Exception("Драйвер по запросу клиента не найден"); } //отправляем запрос драйверу simpMessagingTemplate.convertAndSendToUser(closestTrack.getVehicle().getDriverUser().getEmailAddress(), "/topic/customer-trip",customerTrip); log.info("отправка запроса водителю с идентификатором: {} на запрос клиента: {}", БлижайшийTrack.getVehicle().getDriverUser().getId(), customerTrip); }); } Интерфейс React useEffect(() => { const token = localStorage.getItem('токен'); константный клиент = новый клиент({ brokerURL: 'ws://localhost:8081/massitec', ConnectHeaders: { Авторизация: `Носитель ${токен}`, }, задержка повторного подключения: 5000, HeartbeatIncoming: 4000, onConnect: () => { console.log('Подключено к брокеру', client.connected) client.subscribe('/user/topic/customer-trip', message => { const msg = JSON.parse(message.body); console.log('Сообщение получено: ', msg.message); if (msg.message === 'Ищем для вас водителя, вы получите уведомление, когда водитель примет ваш запрос') { глоток({ title: 'Драйвер найден!', текст: 'Водитель принял ваш запрос. Пожалуйста, проверьте свою панель управления для получения более подробной информации.', значок: «успех», ConfirmButtonText: 'ОК', }); Navigation("/customer-dashboard", { replace: true }); } else if (msg.message === 'Драйвер по вашему запросу не найден') { глоток({ title: «Драйвер не найден!», текст: «К сожалению, в данный момент драйвер недоступен. Пожалуйста, повторите попытку позже.', значок: «ошибка», ConfirmButtonText: 'ОК', }); } }); }, onStompError: (кадр) => { console.log('Брокер сообщил об ошибке: ' +frame.headers['message']); console.log('Дополнительная информация: ' +frame.body); console.log('Ошибка STOMP: ', кадр); }, }); клиент.активировать(); }, []);
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»