【springboot】sse接口

导读:本篇文章讲解 【springboot】sse接口,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一.效果示例

请添加图片描述

二.代码示例

1.controller层
package com.xiaoi.xics.forward.interfaces;

import com.xiaoi.xics.core.tool.api.R;
import com.xiaoi.xics.forward.application.service.IMessageService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;


/**
 * @Description sse
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/sse")
public class SseController {

    private IMessageService messageService;

    @PostMapping(value="/push")
    @ApiOperation(value = "推送")
    public R<String> push(@RequestParam("message") String message){
        return R.status(messageService.push(message));
    }
	
	// 允许跨域
    @CrossOrigin
    @GetMapping(value="/get",produces = "text/event-stream;charset=UTF-8" )
    @ApiOperation(value = "获取")
    public String get(){
        try {
            return "data:" + messageService.get()+ "\n\n";
        }catch (Exception e) {
            e.printStackTrace();
            return "data:" +"{\"msg\":\"fail\",\"code\":1, \"error\": "+ e.getMessage() +"}" + "\n\n";
        }
        // 注意,EventSource返回的参数必须以data:开头,"\n\n"结尾,否则onmessage方法无法执行
    }
}

2.service层
package com.xiaoi.xics.forward.application.service.impl;

import com.xiaoi.xics.forward.application.service.IMessageService;
import com.xiaoi.xics.forward.domain.MessageDomain;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @Description 消息服务
 */
@Service
@AllArgsConstructor
public class MessageServiceImpl implements IMessageService {
    private MessageDomain messageDomain;

    public Boolean push(String message) {
        return messageDomain.push(message);
    }

    public String get() {
        return messageDomain.get();
    }
}

3.domain层
package com.xiaoi.xics.forward.domain;

import com.xiaoi.xics.core.log.exception.ServiceException;
import com.xiaoi.xics.core.tool.support.Kv;
import com.xiaoi.xics.core.tool.utils.Func;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Description redis消息
 */
@Service
@AllArgsConstructor
public class MessageDomain {
    private RedisTemplate redisTemplate;

    public Boolean push(String message) {
        try {
            if(Func.isEmpty(message)){
                throw new ServiceException("message不能为空");
            }
            redisTemplate.opsForList().leftPush("xiaoi:message", message);
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public String get() {
        Kv kv = Kv.create();
        try {
            Object o = redisTemplate.opsForList().rightPop("xiaoi:message");
            if(Func.isNotEmpty(o)){
                kv.put("msg", (String) o);
                kv.put("success", true);
            }else{
                kv.put("msg", "");
                kv.put("success", true);
            }
        }catch(Exception e){
            e.printStackTrace();
            kv.put("msg", "");
            kv.put("success", false);
            kv.put("error", e.getMessage());
        }
        return kv.toString();
    }
}
4.application配置
server:
  port: 8080
spring:
  redis:
    #redis 单机环境配置
    host: 127.0.0.1
    port: 6379
    password:
    database: 9
    ssl: false
5.html测试
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">  
//需要判断浏览器支不支持,可以去w3c进行查看
var source = new EventSource('http://localhost:8080/sse/get');
source.onmessage = function (event) {
  console.info(event.data);
  document.getElementById('result').innerText = event.data
};
 
</script>  
</head>
 
<body>
    <div id="result"></div>  
</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92338.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!