具有Sseemitter 406错误的jhipster微服务

时间:2018-10-23 14:15:45

标签: angular spring-boot server-sent-events

我用网关uaa和微服务生成了jhipster应用程序。现在要运行sse,我添加了以下控制器

@RestController
@RequestMapping("/api")
public class AvgResultNftController {

    private final CopyOnWriteArrayList<SseEmitter> emitters = new CopyOnWriteArrayList<>();

    @GetMapping(path = "/avgResultNft")
    public SseEmitter getAvgResultNft() {
        SseEmitter emitter = new SseEmitter();
        this.emitters.add(emitter);

        emitter.onCompletion(() -> this.emitters.remove(emitter));
        emitter.onTimeout(() -> {
            emitter.complete();
            this.emitters.remove(emitter);
        });
        return emitter;
    }



    @SuppressWarnings("unlikely-arg-type")
    @EventListener
    public void onAvgResultNft(AvgResultNft avgResultNft) {
        List<SseEmitter> deadEmitters = new ArrayList<>();
        this.emitters.forEach(emitter -> {
            try {
                emitter.send(avgResultNft);
            } catch (Exception e) {
                deadEmitters.add(emitter);
            }
        });
        this.emitters.remove(deadEmitters);
    }

}

我正在某个事件上发布AvgResultNft。

我已经生成了角度应用程序并像这样调用控制器

let source = new EventSource('http://192.168.1.5:8080/proxta/api/avgResultNft', {withCredentials: true })
source.addEventListener('message', message => {
      console.log(message)
    });

我在调用eventSource时收到406不可接受的错误。请帮忙。

1 个答案:

答案 0 :(得分:0)

我认为它可以帮助您  添加headers = "Accept=*/*"produces = MediaType.APPLICATION_OCTET_STREAM_VALUEMediaType.APPLICATION_STREAM_JSON_VALUE

@GetMapping(value = "/avgResultNft", headers = "Accept=*/*",
            produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public SseEmitter getAvgResultNft() {
        SseEmitter emitter = new SseEmitter();
        this.emitters.add(emitter);

        emitter.onCompletion(() -> this.emitters.remove(emitter));
        emitter.onTimeout(() -> {
            emitter.complete();
            this.emitters.remove(emitter);
        });
        return emitter;
    }

但是请注意,zuul1.х不支持sse

How to make Server sent events (SSE) work trough Zuul Proxy spring-boot 2.1.1