解决springboot整合websocket、redis、openfeign,redisTemplate,openfeign的类无法注入的问题

本文描述了在SpringBoot应用中使用WebSocket和FeignClient时遇到的空指针问题,通过调整启动类和引入ApplicationContextHelper辅助类,解决了依赖注入问题,并提供了测试方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在部分业务中,我们需要使用长连接,我们可以使用http长连接或者websocket,在springboot作为后端的框架中, 可以借用的技术是(netty,websocket)

版本如下 

软件版本号
jdk21
springboot

3.1.5

springcloud

2022.0.4

 场景复现

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>testDi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>testDi</name>
    <description>testDi</description>
    <properties>
        <java.version>21</java.version>
        <spring-cloud.version>2022.0.4</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 配置类

package com.example.testdi.config;

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

@Configuration
public class WebsocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192 * 4);
        container.setMaxBinaryMessageBufferSize(8192 * 4);
        return container;
    }
}

rpc类

package com.example.testdi.rpc;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@FeignClient(value = "http://localhost:9090")
public interface TestRpc {

    @GetMapping("/hello")
    @ResponseBody
    String hello();
}

websocket类

@Slf4j
@Component
@ServerEndpoint(value = "/example")
public class ExampleWebsocket {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private TestRpc testRpc;

    @OnOpen
    public void open(Session session) {
        log.info("===============open=================");
        log.info("redisTemplate: {}", redisTemplate);
        log.info("testRpc: {}", testRpc);
    }
}

启动类

@EnableFeignClients
@SpringBootApplication
public class TestDiApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestDiApplication.class, args);
    }

}

配置文件

spring:
  data:
    redis:
      host: xxx.xxx.xxx.xxx
      database: xx
      port: xxxx
      timeout: xxxx
      password: xxxxxxxxxxxxxxx
server:
  port: 9090

效果

可以看到都是空指针

问题分析

可能是bean没有注入到spring容器吗?

修改启动类

package com.example.testdi;

import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ApplicationContext;

import java.util.Arrays;
import java.util.List;

@EnableFeignClients
@SpringBootApplication
public class TestDiApplication extends SpringBootServletInitializer implements CommandLineRunner {

    @Resource
    private ApplicationContext appContext;

    public static void main(String[] args) {
        SpringApplication.run(TestDiApplication.class, args);
    }


    @Override
    public void run(String... args) throws Exception
    {
        String[] beans = appContext.getBeanDefinitionNames();
        Arrays.sort(beans);
        List<String> list = Arrays.stream(beans).filter(ele -> ele.contains("TestRpc") || ele.contains("redisTemplate")).toList();
        for (String bean : list)
        {
            System.out.println(bean + " of Type :: " + appContext.getBean(bean).getClass());
        }
    }
}

查看控制台

发现并不是上述情况

没获取到/获取的方式错误

解决方案 

使用辅助类

package com.example.testdi.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationHelper.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

}

修改websocket代码

package com.example.testdi.websocket;

import com.example.testdi.rpc.TestRpc;
import com.example.testdi.utils.ApplicationHelper;
import jakarta.annotation.Resource;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ServerEndpoint(value = "/example")
public class ExampleWebsocket {

    private RedisTemplate<String, Object> redisTemplate= (RedisTemplate<String, Object>) ApplicationHelper.getBean("redisTemplate");

    private TestRpc testRpc= (TestRpc) ApplicationHelper.getBean("com.example.testdi.rpc.TestRpc");

    @OnOpen
    public void open(Session session) {
        log.info("===============open=================");
        log.info("redisTemplate: {}", redisTemplate);
        log.info("testRpc: {}", testRpc);
    }
}

效果

一些问题 

怎么测试websocket接口

这里推荐2个,一个是postman,一个是网站

postman 

即可开始测试

网站

这边推荐测试网站测试,支持ws/wss

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值