springboot框架嵌入netty
1.pom.xml添加依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
2.application.properties集成netty
tcp.port=8081
boss.thread.count=200
worker.thread.count=200
so.keepalive=true
so.backlog=100
3.Configuration类
package com.adc.config;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Set; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import com.adc.netty.StringProtocolInitalizer; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
@Configuration
public class NettyConfig {
@Value("${boss.thread.count}")
private int bossCount; @Value("${worker.thread.count}")
private int workerCount; @Value("${tcp.port}")
private int tcpPort; @Value("${so.keepalive}")
private boolean keepAlive; @Value("${so.backlog}")
private int backlog;
@Autowired
@Qualifier("springProtocolInitializer")
private StringProtocolInitalizer protocolInitalizer; @SuppressWarnings("unchecked")
@Bean(name = "serverBootstrap")
public ServerBootstrap bootstrap() {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup(), workerGroup())
.channel(NioServerSocketChannel.class)
.childHandler(protocolInitalizer);
Map<ChannelOption<?>, Object> tcpChannelOptions = tcpChannelOptions();
Set<ChannelOption<?>> keySet = tcpChannelOptions.keySet();
for (@SuppressWarnings("rawtypes")
ChannelOption option : keySet) {
b.option(option, tcpChannelOptions.get(option));
}
return b;
} @Bean(name = "bossGroup", destroyMethod = "shutdownGracefully")
public NioEventLoopGroup bossGroup() {
return new NioEventLoopGroup(bossCount);
} @Bean(name = "workerGroup", destroyMethod = "shutdownGracefully")
public NioEventLoopGroup workerGroup() {
return new NioEventLoopGroup(workerCount);
}
@Bean(name = "tcpSocketAddress")
public InetSocketAddress tcpPort() {
return new InetSocketAddress(tcpPort);
} @Bean(name = "tcpChannelOptions")
public Map<ChannelOption<?>, Object> tcpChannelOptions() {
Map<ChannelOption<?>, Object> options = new HashMap<ChannelOption<?>, Object>();
options.put(ChannelOption.SO_KEEPALIVE, keepAlive);
options.put(ChannelOption.SO_BACKLOG, backlog);
return options;
} @Bean(name = "stringEncoder")
public StringEncoder stringEncoder() {
return new StringEncoder();
} @Bean(name = "stringDecoder")
public StringDecoder stringDecoder() {
return new StringDecoder();
} /**
* Necessary to make the Value annotations work.
*
* @return
*/
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
4.初始化类
package com.adc.netty; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; /**
* Just a dummy protocol mainly to show the ServerBootstrap being initialized.
*
* @author Abraham Menacherry
*
*/
@Component
@Qualifier("springProtocolInitializer")
public class StringProtocolInitalizer extends ChannelInitializer<SocketChannel> { @Autowired
StringDecoder stringDecoder; @Autowired
StringEncoder stringEncoder; @Autowired
ServerHandler serverHandler; @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder", stringDecoder);
pipeline.addLast("handler", serverHandler);
pipeline.addLast("encoder", stringEncoder);
} public StringDecoder getStringDecoder() {
return stringDecoder;
} public void setStringDecoder(StringDecoder stringDecoder) {
this.stringDecoder = stringDecoder;
} public StringEncoder getStringEncoder() {
return stringEncoder;
} public void setStringEncoder(StringEncoder stringEncoder) {
this.stringEncoder = stringEncoder;
} public ServerHandler getServerHandler() {
return serverHandler;
} public void setServerHandler(ServerHandler serverHandler) {
this.serverHandler = serverHandler;
} }
5.逻辑处理类
package com.adc.netty; import java.util.List; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; import com.adc.pojo.TsOrder;
import com.adc.pojo.TsStation;
import com.adc.pojo.TsUser;
import com.adc.service.TsCarService;
import com.adc.service.TsOrderService;
import com.adc.service.TsStationService;
import com.adc.service.TsUserService; import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; @Component
@Qualifier("serverHandler")
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> { private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);
@Autowired
TsCarService carService;
@Autowired
TsUserService userService;
@Autowired
TsOrderService orderService;
@Autowired
TsStationService stationService; @Override
public void messageReceived(ChannelHandlerContext ctx, String msg)
throws Exception {
log.info("client msg:"+msg);
//添加处理请求的逻辑
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("RamoteAddress : " + ctx.channel().remoteAddress() + " active !"); // ctx.channel().writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
ctx.channel().writeAndFlush("connect success"); super.channelActive(ctx);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
// System.out.println(cause.getMessage());
ctx.close();
} @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
log.info("\nChannel is disconnected");
super.channelInactive(ctx);
} private double getdistance(double lat1,double lon1,double lat2,double lon2) {
float earth_radius=6378.137f;
double a=Math.toRadians(lat1)-Math.toRadians(lat2);
double b=Math.toRadians(lon1)-Math.toRadians(lon2);
double distance=2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2), 2)+Math.cos(Math.toRadians(lat1))*Math.cos(Math.toRadians(lat2))*Math.pow(Math.sin(b/2), 2)))
*earth_radius;
return distance;
}
}
springboot框架嵌入netty的更多相关文章
- 纯手写SpringMVC到SpringBoot框架项目实战
引言 Spring Boot其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 通过这种方式,springboot ...
- Springboot框架
本片文章主要分享一下,Springboot框架为什么那么受欢迎以及如何搭建一个Springboot框架. 我们先了解一下Springboot是个什么东西,它是干什么用的.我是刚开始接触,查了很多资料, ...
- Springboot 框架学习
Springboot 框架学习 前言 Spring Boot是Spring 官方的顶级项目之一,她的其他小伙伴还有Spring Cloud.Spring Framework.Spring Data等等 ...
- 小程序后端项目【Springboot框架】部署到阿里云服务器【支持https访问】
前言: 我的后端项目是Java写的,用的Springboot框架.在部署服务器并配置https访问过程中,因为做了一些令人窒息的操作(事后发现),所以老是不能成功. 不成功具体点说就是:域名地址可以正 ...
- springBoot框架的搭建
1新建一个项目: 2.注意选择JDK1.8,和选择spring initializr加载springBoot相关jar包: 3.下一步next: 4.下一步next,选择Web和MyBatis然后ne ...
- 快速搭建springboot框架以及整合ssm+shiro+安装Rabbitmq和Erlang、Mysql下载与配置
1.快速搭建springboot框架(在idea中): file–>new project–>Spring Initializr–>next–>然后一直下一步. 然后复制一下代 ...
- SpringBoot框架的权限管理系统
springBoot框架的权限管理系统,支持操作权限和数据权限,后端采用springBoot,MyBatis,Shiro,前端使用adminLTE,Vue.js,bootstrap-table.tre ...
- atitit.软件开发--socket框架选型--netty vs mina j
atitit.软件开发--socket框架选型--netty vs mina j . Netty是由JBOSS提供的一个java开源框架 Apache mina 三.文档比较 mina文档多,,, 好 ...
- SpringBoot 框架整合
代码地址如下:http://www.demodashi.com/demo/12522.html 一.主要思路 使用spring-boot-starter-jdbc集成Mybatis框架 通过sprin ...
随机推荐
- 翻翻git之---溜的飞起的载入效果AVLoadingIndicatorView
转载请注明出处:王亟亟的大牛之路 由于接近过春节.看各个群体的工作都不太旺盛(不是年会就是各种吹B或是放空). 之前的Material Design的内容差点儿讲的差点儿相同了(至少基本的几个控件都介 ...
- log4net preserveLogFileNameExtension 和 watch
preserveLogFileNameExtension <log4net> <appender name="fileappender" type="l ...
- .Net-ASP.NET Web API:目录
ylbtech-.Net-ASP.NET Web API:目录 1.返回顶部 2.返回顶部 3.返回顶部 4.返回顶部 5.返回顶部 0. https://www.asp.net/we ...
- Gym - 101981A The 2018 ICPC Asia Nanjing Regional Contest A.Adrien and Austin 简单博弈
题面 题意:一堆有n个石子,编号从1⋯N排成一列,两个人Adrien 和Austin玩游戏,每次可以取1⋯K个连续编号的石子,Adrien先手,谁不能取了则输 题解:k==1时,显然和n奇偶相关,当k ...
- [Apple开发者帐户帮助]三、创建证书(8)撤销证书
您可以根据证书类型和角色撤消证书.有关详细信息,请转到撤消权限. 要了解撤销证书时会发生什么,请转到Apple Developer支持中的证书. 所需角色:帐户持有人或管理员. 在“ 证书”,“标识符 ...
- POJ 1149 PIGS (AC这道题很不容易啊)网络流
PIGS Description Mirko works on a pig farm that consists of M locked pig-houses and Mirko can't unlo ...
- ACM_城市交通线(简单并查集)
城市交通线 Time Limit: 2000/1000ms (Java/Others) Problem Description: A国有n座城市,编号为1~n,这n个城市之间没有任何交通线路,所以不同 ...
- C# Area 双重路由如何写
在WebApi项目里面 一般除了接口, 还有管理端...一些乱七八糟的,你想展示的东西, 一种做法是分开写: 比如管理后台一个项目, 然后接口一个, 然后页面一个, 其实这样做也可以,但是这么做, 无 ...
- 【WPF】使用 XAML 的 Trigger 系统实现三态按钮
利用 WPF 的 Trigger 系统,也可以很简单的只使用xmal实现三态按钮.在Window或UserControl的资源中声明按钮的style并加入触发功能.使用的时候直接在button里复写s ...
- CSS元素水平垂直居中的方法
1. 元素水平居中 1.1 设置父元素的属性 text-align: center; 说明:此属性只针对父元素的子元素为内联元素时有效,比如:img,input,select,button等(行内 ...