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 ...
随机推荐
- MFC 小知识总结四
1 PlaySound 播放WAV格式的音乐 This function plays a sound specified by a file name, resource, or system ev ...
- pytest 失败用例重试
https://www.cnblogs.com/jinzhuduoduo/articles/7017405.html http://www.lxway.com/445949491.htm https: ...
- luogu3358 最长k可重区间集问题 网络流
题目大意: 关键词:最小费用最大流 不相交路径 如果两个线段重叠了,那我们则把一个线段放在下一层,另一个线段放在上一层.把流量为1的流看作一条线,一条线把位于同一层的线段(互不重叠)都串了起来.最多有 ...
- string[][]和string[,] 以及 int[][]和int[,]
string[][]和string[,] http://www.codewars.com/kata/56f3a1e899b386da78000732/train/csharp Write a func ...
- 循环遍历Java字符串字符的规范方法——类似python for ch in string
比如我将string作为CNN 文本处理输入: float [] input = new float[maxLength]; // 1 sentence by maxLenWords // int[] ...
- The Moronic Cowmpouter(负进位制转换)
http://poj.org/problem?id=3191 题意:将一个整型的十进制整数转化为-2进制整数. #include <stdio.h> #include <algori ...
- Django day06 模版层(一) 变量和深度查询
一.模版语法之变量: 1 - {{ 变量 }} ******重要*******{#这个相当于print了该变量#} def index(request): name = 'prince' #字符串 ...
- tp 3.1.3 动态切换模板问题
if($this->isMobile()) { C('DEFAULT_THEME', 'mobile'); // 这里定义手机模板目录 C('TMPL_CACHE_PREFIX', 'm_'); ...
- jvm堆外直接内存实现高性能接入层
jvm堆外直接内存实现高性能接入层https://blog.csdn.net/phil_code/article/details/69056086
- VMWare 在物理机待机后,报错“该虚拟机似乎正在使用中”
在物理机待机后,刚打开虚拟机,就弹出这个画面(这种情况经常出现在远程之后,本机待机之后) 点击确定后,就弹出 当点击取消,无反应,而且再次点击VM2又弹出以上窗口,点击获取所有权,则弹出以下窗口 上网 ...