栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

项目实训(9) - 其它

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

项目实训(9) - 其它

文章目录
  • 前言
  • https
    • yaml文件
    • http请求转发https
  • 服务降级
  • 聊天的心跳检测
  • 同一个账户重复连接问题


前言

项目实训快要答辩了,这里就记录一些之前没写的内容。

https

在网关配置了https

yaml文件
server:
  port: 8443
  ssl:
    key-store: classpath:ssl.pfx
    key-store-password: 密码
    enabled: true
    key-store-type: PKCS12
  max-http-header-size: 16384

获取证书(证书是同学给的),将证书转换成pfx文件(一些网站能做到),将pfx文件放置在resources目录下。

http请求转发https

注册bean servletContainer和httpConnector,http监听8080端口转发8443。注意在servletContainer()中的connection.addMethod(DEFAULT_PROTOCOL);,最开始写的时候没有添加这一句,之后测试的时候发现发送的post请求转发成get请求,一直给我报method not allowed。

package com.meeting.gateway.config;

import com.meeting.common.util.JwtTokenUtil;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

@Configuration
public class Config {

    @Bean
    public JwtTokenUtil jwtTokenUtil() {
        return new JwtTokenUtil();
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        builder.setConnectTimeout(Duration.ofMillis(8 * 1000));
        builder.setReadTimeout(Duration.ofMillis(8 * 1000));
        return builder.build();
    }

    
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("
    private final AtomicInteger controller = new AtomicInteger(3000);
    
    
    public int degrade() {
        return controller.decrementAndGet();
    }

    
    public void upgrade() {
        controller.incrementAndGet();
    }
    
}
@Order(3)
@Component
@WebFilter(filterName = "RoutingFilter", urlPatterns = {"/*"})
public class RoutingFilter implements Filter {
	@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        ResponseData responseData = null;

        String uri = request.getRequestURI();
        Service service = getService(router.getServices(), uri);
        if (service == null) {
            logger.error("访问{},服务不存在", uri);
            responseData = new ResponseData(404, "不存在的服务");
            response.setStatus(404);
        } else {
            if (service.degrade() <= 0) {
                logger.info("访问{},服务降级", uri);
                responseData = new ResponseData(400, "服务繁忙,稍后再试");
                response.setStatus(400);
            } else {
               // 正常执行,之前贴过代码了
            }
            service.upgrade();
        }
        byte[] bytes = JSON.toJSONBytes(responseData);
        request.setAttribute("bytes", bytes);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

    }
}
聊天的心跳检测

netty服务器启动。

private void startServer() {
        //服务端需要2个线程组  boss处理客户端连接  work进行客服端连接之后的处理
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            //服务器 配置
            bootstrap.group(boss,work).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline()
                                    // 超过30秒没有写,触发写超时
                                    .addLast("idle-state", new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS))
                                    // HttpServerCodec:将请求和应答消息解码为HTTP消息
                                    .addLast("http-codec",new HttpServerCodec())
                                    // HttpObjectAggregator:将HTTP消息的多个部分合成一条完整的HTTP消息
                                    .addLast("aggregator",new HttpObjectAggregator(65536))
                                    // ChunkedWriteHandler:向客户端发送HTML5文件
                                    .addLast("http-chunked",new ChunkedWriteHandler())
                                    // .addLast("websocket", new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10))
                                    // 配置通道处理来进行业务处理
                                    .addLast("handler", new WebSocketHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childOption(ChannelOption.SO_KEEPALIVE,true);
            //绑定端口  开启事件驱动
            Channel channel = bootstrap.bind(port).sync().channel();
            channel.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }

WebSocketHandler

	private AtomicBoolean isFirst = new AtomicBoolean(true);
	
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (!(evt instanceof IdleStateEvent)) {
            super.userEventTriggered(ctx, evt);
        } else {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                // 读写空闲,断开连接
                final Channel channel = ctx.channel();
                if (isFirst.getAndSet(false)) {
                    // 第一次读写超时,发送心跳包
                    sendMessageToChannel(channel, ResponseData.HEARTBEAT);
                } else {
                    // 第二次读写超时,断开连接
                    ChannelFuture close = ctx.close();
                    close.addListener(future -> chatChannelGroup.removeChannel(channel));
                }
            }
        }
    }

	@Override
    public void channelRead0(ChannelHandlerContext ctx, Object data) throws Exception {
        if (data instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) data);
        } else if (data instanceof TextWebSocketFrame) {
            isFirst.set(true);
            handleWebSocketFrame((TextWebSocketFrame) data);
        }
    }

这样,超时后,服务器就会断开连接。

同一个账户重复连接问题

之前为了方便,重复连接会拒绝第二个连接,现在改成将第一个连接断开,不过,由于能力有限,对netty的异步机制不是很了解,改成了在同一个账户第二次连接时,向第一次连接发送数据,然后从服务器保存的数据中删除第一次连接(注意,此时连接并没有断开),并添加第二次连接。第一次连接是由客户端收到数据后主动断开的。
netty发送数据是异步的,虽然可以通过future.addListener来实现发送完成后再断开连接,但是,我不确定如果发送数据因为一些原因一直没有完成会怎么样,所以,由客户端主动断开连接。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/950951.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号