基于SpringBoot注入Bean形式的监听(端口)

本文介绍了如何在SpringBoot应用中创建一个监听特定端口的Bean,使用`CommandLineRunner`启动监听,当接收到连接时处理客户端请求并将其保存到数据库。PortListenerService负责监听和客户端通信的逻辑。

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

起一个线程、监听对应的端口,注入到容器

package com.port.component;

import com.port.service.PortListenerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


/**
 * @Description: 监听端口bean
 * @author: be_insighted
 * @create: 2024/4/1 15:09
 * @since 1.0.0
 */



@Component
public class AppRunner implements CommandLineRunner {

    @Value("${listener-port}")
    private int listenPort;

    private final PortListenerService portListenerService;

    public AppRunner(PortListenerService portListenerService) {
        this.portListenerService = portListenerService;
    }

    @Override
    public void run(String... args) throws Exception {
        portListenerService.startListening(listenPort); // 开始监听端口
    }
}

Port Listener进行逻辑处理,注入到容器

package com.port.service;

/**
 * @Description: 端口监听逻辑层
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值