若依(ruoyi/ruoyi-vue)集成websocket以及ws配置匿名访问

若依集成websocket实现实时通信

需要按照具体情况进行操作对于某些时候可能有相对改动

WebSocket是一种通信协议,可在单个TCP连接上进行全双工通信。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就可以建立持久性的连接,并进行双向数据传输。

1、ruoyi-framework/pom.xml文件添加websocket依赖。

<!-- SpringBoot Websocket -->
<dependency>  
   <groupId>org.springframework.boot</groupId>  
   <artifactId>spring-boot-starter-websocket</artifactId>  
</dependency>

2、配置匿名访问

- shiro安全框架

// 如果需要不登录也可以访问,需要设置匿名访问
filterChainDefinitionMap.put("/websocket/**", "anon");

- springScecurity

//位置 class com.aries.framework.config.SecurityConfig;

//忽略websocket拦截
    @Override
    public void configure(WebSecurity webSecurity) {
   
        webSecurity.ignoring().antMatchers("/websocket/**");
    }

3、将以下代码创建到对应位置,每一个代码块的第一行是对应的位置,这里仅仅只写出ruiyi分离版的,首先在framwork模块framwork包中创建websocker包然后分别创建对应的class文件,并且将下方代码复制进去

SemaphoreUtils : 信号量相关处理

package com.ruoyi.framework.websocket;

import java.util.concurrent.Semaphore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 信号量相关处理
 * 
 * @author ruoyi
 */
public class SemaphoreUtils
{
   

    /**
     * SemaphoreUtils 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SemaphoreUtils.class);

    /**
     * 获取信号量
     * 
     * @param semaphore
     * @return
     */
    public static boolean tryAcquire(Semaphore semaphore)
    {
   
        boolean flag = false;

        try
        {
   
            flag = semaphore.tryAcquire();
        }
        catch (Exception e)
        {
   
            LOGGER.error("获取信号量异常", e);
        }

        return flag;
    }

    /**
     * 释放信号量
     * 
     * @param semaphore
     */
    public static void release(Semaphore semaphore)
    {
   

        try
        {
   
            semaphore.release();
        }
        catch (Exception e)
        {
   
            LOGGER.error("释放信号量异常", e);
        }
    }
}

WebSocketConfig : websocket 配置

package com.ruoyi.framework.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * websocket 配置
 * 
 * @author ruoyi
 */
@Configuration
public class WebSocketConfig
{
   
    @Bean
    public ServerEndpointExporter serverEndpointExporter()
    {
   
        return new ServerEndpointExporter();
    }
}

WebSocketServer : websocket 消息处理

package com.ruoyi.framework.websocket;

import 
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

社畜阿藏405

挣点钱不丢人吧?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值