spring 如何存储WebSocket的“第一条消息”(使用java)

yftpprvb  于 2022-10-31  发布在  Spring
关注(0)|答案(1)|浏览(170)

我做了一个警报函数,它从WebSocket获取价格数据,如果条件满足就发送警报。我现在只有“价格条件”,我想添加“百分比条件”。所以我想做的是
1.打开WebSocket
1.取得第一资料,计算限价
1.例如)用户希望在价格下降5%时得到提醒。
1.打开WebSocket,当前价格是100$
1.因此,我需要在价格达到95美元(限制价格)时向用户发送警报
要做到这一点,我需要计算限价时,打开WebSocket。但我不知道“在哪里和如何”,我可以存储限价。
这是我的WebSocket代码实现价格条件(而不是“百分比条件”)

Web套接字客户端端点

@ClientEndpoint
public class WebsocketClientEndpoint {
    Session userSession = null;
    private MessageHandler messageHandler;

    public WebsocketClientEndpoint() {
    }

    public Session connect(URI endpointURI) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            userSession = container.connectToServer(this, endpointURI);

            return userSession;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Callback hook for Connection open events.
     *
     * @param userSession the userSession which is opened.
     */
    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println("opening websocket");
        this.userSession = userSession;
    }

    /**
     * Callback hook for Connection close events.
     *
     * @param userSession the userSession which is getting closed.
     * @param reason the reason for connection close
     */
    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println("closing websocket");
        this.userSession = null;
    }

    /**
     * Callback hook for Message Events. This method will be invoked when a client send a message.
     *
     * @param message The text message
     */
    @OnMessage
    public void onMessage(String message) throws ParseException, IOException {

        if (this.messageHandler != null) {
            this.messageHandler.handleMessage(message);
        }
    }

    @OnMessage
    public void onMessage(ByteBuffer bytes) {
        System.out.println("Handle byte buffer");
    }

    /**
     * register message handler
     *
     * @param msgHandler
     */
    public void addMessageHandler(MessageHandler msgHandler) {
        this.messageHandler = msgHandler;
    }

    /**
     * Send a message.
     *
     * @param message
     */
    public void sendMessage(String message) {
        this.userSession.getAsyncRemote().sendText(message);
    }

    /**
     * Message handler.
     *
     * @author Jiji_Sasidharan
     */
    public static interface MessageHandler {
        public void handleMessage(String message) throws ParseException, IOException;
    }
}

按价格提醒用户

public void AlertUserByPrice(Long id) {
Alert alert = alertRepository.findById(id).orElseThrow(() -> new NoSuchElementException());

String type = alert.getAlertType().getKey();

double SetPrice = alert.getPrice();
 String ticker = alert.getTicker();

JSONParser jsonParser = new JSONParser();

final NotificationRequest build;

if (type == "l_break") {
    build = NotificationRequest.builder()
            .title(ticker + " alert")
            .message(SetPrice + "broke down")
            .token(notificationService.getToken(userDetailService.returnUser().getEmail()))
            .build();
}
else { // upper_break
    build = NotificationRequest.builder()
            .title(ticker + " alert")
            .message(SetPrice + "pierced upward")
            .token(notificationService.getToken(userDetailService.returnUser().getEmail()))
            .build();
}

try {
    final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint();

    Session session = clientEndPoint.connect(new URI("wss://ws.coincap.io/prices?assets=" + ticker));

    WebsocketClientEndpoint.MessageHandler handler = new WebsocketClientEndpoint.MessageHandler() {
        public void handleMessage(String message) throws ParseException, IOException {
            Object obj = jsonParser.parse(message);

            JSONObject jsonObject = (JSONObject) obj;

            double price = Double.parseDouble(jsonObject.get(ticker).toString());

            System.out.println("가격 : " + price);

            if (type == "l_break") {
                if (price < SetPrice) {
                    System.out.println("끝");
                    notificationService.sendNotification(build);
                    session.close();
                }
            } else {
                if (price > SetPrice) {
                    System.out.println("끝");
                    notificationService.sendNotification(build);
                    session.close();
                }
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                System.err.println("InterruptedException exception: " + ex.getMessage());
            }
        }
    };
    clientEndPoint.addMessageHandler(handler);

} catch (URISyntaxException ex) {
    System.err.println("URISyntaxException exception: " + ex.getMessage());
}
}

我该怎么做才能实现“按血统条件报警”??请有人帮忙..提前感谢

zte4gxcn

zte4gxcn1#

double percent = 0.05;
if (price-(price*percent) < SetPrice) {
                    System.out.println("끝");
                    notificationService.sendNotification(build);
                    session.close();
}

if (price-(price*percent) > SetPrice) {
                    System.out.println("끝");
                    notificationService.sendNotification(build);
                    session.close();
                }

如果有帮助,请尝试

相关问题