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的更多相关文章

  1. 纯手写SpringMVC到SpringBoot框架项目实战

    引言 Spring Boot其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 通过这种方式,springboot ...

  2. Springboot框架

    本片文章主要分享一下,Springboot框架为什么那么受欢迎以及如何搭建一个Springboot框架. 我们先了解一下Springboot是个什么东西,它是干什么用的.我是刚开始接触,查了很多资料, ...

  3. Springboot 框架学习

    Springboot 框架学习 前言 Spring Boot是Spring 官方的顶级项目之一,她的其他小伙伴还有Spring Cloud.Spring Framework.Spring Data等等 ...

  4. 小程序后端项目【Springboot框架】部署到阿里云服务器【支持https访问】

    前言: 我的后端项目是Java写的,用的Springboot框架.在部署服务器并配置https访问过程中,因为做了一些令人窒息的操作(事后发现),所以老是不能成功. 不成功具体点说就是:域名地址可以正 ...

  5. springBoot框架的搭建

    1新建一个项目: 2.注意选择JDK1.8,和选择spring initializr加载springBoot相关jar包: 3.下一步next: 4.下一步next,选择Web和MyBatis然后ne ...

  6. 快速搭建springboot框架以及整合ssm+shiro+安装Rabbitmq和Erlang、Mysql下载与配置

    1.快速搭建springboot框架(在idea中): file–>new project–>Spring Initializr–>next–>然后一直下一步. 然后复制一下代 ...

  7. SpringBoot框架的权限管理系统

    springBoot框架的权限管理系统,支持操作权限和数据权限,后端采用springBoot,MyBatis,Shiro,前端使用adminLTE,Vue.js,bootstrap-table.tre ...

  8. atitit.软件开发--socket框架选型--netty vs mina j

    atitit.软件开发--socket框架选型--netty vs mina j . Netty是由JBOSS提供的一个java开源框架 Apache mina 三.文档比较 mina文档多,,, 好 ...

  9. SpringBoot 框架整合

    代码地址如下:http://www.demodashi.com/demo/12522.html 一.主要思路 使用spring-boot-starter-jdbc集成Mybatis框架 通过sprin ...

随机推荐

  1. MySql免安装版l配置方法

    初次接触mysql,折腾了一天,总是安装不成功,服务启动不了.后来从官网下载了ZIP Archive版,不用安装,直接把它解压到磁盘,做一些简单的配置就可以. 软件下载地址:http://dev.my ...

  2. Windows移动开发(五)——初始XAML

    关于详细的基本功就先说这么多.后面遇到再补充说明,前面说的都是一些代码和原理方面的东西.接下来说的会有界面和代码结合,会有成就感,由于能真正的做出东西来了. Windows移动开发包含Windows ...

  3. centos改动sshport

    vi /etc/ssh/sshd_config 找到#Port 22一段,这里是标识默认使用22port.加入一行例如以下: Port 34981 然后保存退出 然后service sshd rest ...

  4. MapReduce:具体解释Shuffle过程

    Shuffle过程是MapReduce的核心,也被称为奇迹发生的地方.要想理解MapReduce, Shuffle是必需要了解的.我看过非常多相关的资料,但每次看完都云里雾里的绕着,非常难理清大致的逻 ...

  5. hdu1116 Play on Words--并查集

    原题链接: pid=1116">http://acm.hdu.edu.cn/showproblem.php? pid=1116 一:原题内容 Problem Description S ...

  6. poj 2351 Farm Tour (最小费用最大流)

    Farm Tour Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 17230   Accepted: 6647 Descri ...

  7. 5-8 第五天 微信 JS-SDK

    SDK的难点不多,但是容易出错的地方特别多.几乎任何一个环节都会犯错误. 难道没有域名就不让你测了吗?别担心,有公众测试号, 域名这个代理呢是通过QQ浏览器的服务器调试,来绑定这个端口的,把这个服务开 ...

  8. ReverseEngineerCodeFirst 自定义模板

    1.在你要生成的项目里面在根目录下面添加CodeTemplates文件夹,并在该文件夹下面创建子文件夹ReverseEngineerCodeFirst 2.在ReverseEngineerCodeFi ...

  9. 工具分享1:文本编辑器EditPlus、汇编编译器masm、Dos盒子

    工具已打包好,需要即下载 链接 https://pan.baidu.com/s/1dvMyvW 密码 mic4

  10. SQLServer2008 有用的判断函数

    ISNULL(参数1,参数2) 若参数1为空,则返回参数2 NULLIF(参数1,参数2) 若参数1和参数2不等,则返回参数1 若参数1和参数2相等,则返回NULL 例子:ISNULL(NULLIF( ...