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. [RxJS 6] The Retry RxJs Error Handling Strategy

    When we want to handle error observable in RxJS v6+, we can use 'retryWhen' and 'delayWhen': const c ...

  2. 中国银联mPOS通用技术安全分析和规范解读

    mPOS是近年出现并得到迅速发展的一种新型受理产品,不少机构和生产企业进行了各种形式的试点. 因为mPOS引入了手机.平板电脑等通用智能移动设备.并通过互联网进行信息传输.因此其安全特点与传统银行卡受 ...

  3. 【翻译自mos文章】在12c数据库中,哪种audit trail 受到支持?

    在12c数据库中,哪种audit trail 受到支持? 来源于:What Audit Trail Types Are Supported For A 12c Database? (文档 ID 198 ...

  4. 【IOS 开发】Object - C 入门 之 数据类型具体解释

    作者 : 韩曙亮 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/38544659 1. 数据类型简单介绍及输出 (1) 数据类型 ...

  5. tensorflow在windows操作系统上的安装

    在电脑上安装PyCharm和Python3,然后把Python3的安装路径写进系统变量里,Python安装完之后, https://bootstrap.pypa.io/get-pip.py,把这页的代 ...

  6. C++ this指针 全部

    在每一个成员函数中都包含一个特殊的指针,这个指针的名字是固定的.叫做this.它是指向本类对象的指针,它的值是当前被调用的成员函数所在的对象的起      始地址.例如:当调用成员函数a.volume ...

  7. bzoj3436: 小K的农场(差分约束)

    3436: 小K的农场 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 1575  Solved: 690[Submit][Status][Discus ...

  8. Mock实现模拟python的对象

    Mock库的应用 Mock在Python3.3之前是第三方库,需要安装 pip install Mock :导入 import mock Mock在Python3.3之后是Python标准库,导入方式 ...

  9. JPA实体关联关系,一对一以及转换器

    现有两张表 room (rid,name,address,floor) room_detail (rid,roomid,type) 需要创建房间实体,但是也要包含type属性 @Data //lamb ...

  10. (三)Appium-desktop 打包

    appium-desktop经过二次开发后,需要打包为应用提供给其它同学使用.我们知道appium-desktop是使用electron来构建跨平台桌面应用程序.electron有electron-p ...