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

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

版本如下 

软件 版本号
jdk 21
springboot

3.1.5

springcloud

2022.0.4

 场景复现

pom文件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        3.1.5
         
    
    com.example
    testDi
    0.0.1-SNAPSHOT
    testDi
    testDi
    
        21
        2022.0.4
    
    
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            org.springframework.boot
            spring-boot-starter-websocket
        
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
        
            org.springframework.cloud
            spring-cloud-starter-loadbalancer
        
        
            org.projectlombok
            lombok
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


 配置类

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 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 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 redisTemplate= (RedisTemplate) 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);
    }
}

效果

解决springboot整合websocket、redis、openfeign,redisTemplate,openfeign的类无法注入的问题_第1张图片

一些问题 

怎么测试websocket接口

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

postman 

解决springboot整合websocket、redis、openfeign,redisTemplate,openfeign的类无法注入的问题_第2张图片

解决springboot整合websocket、redis、openfeign,redisTemplate,openfeign的类无法注入的问题_第3张图片

即可开始测试

网站

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

你可能感兴趣的:(springboot,spring,boot,websocket,redis,springcloud,openfeign)