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. OllyDbg 使用笔记 (七)

    OllyDbg 使用笔记 (七) 參考 书:<加密与解密> 视频:小甲鱼 解密系列 视频 演示样例程序下载:http://pan.baidu.com/s/1gvwlS 暴力破解 观察这个程 ...

  2. java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

    1.错误描写叙述 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String service. ...

  3. 【LeetCode OJ 232】Implement Queue using Stacks

    题目链接:https://leetcode.com/problems/implement-queue-using-stacks/ 题目:Implement the following operatio ...

  4. CocoaPods建立私有仓库

    项目管理:CocoaPods建立私有仓库 2015-05-08 10:22 编辑: lansekuangtu 分类:iOS开发 来源:agdsdl 0 6367 CocoaPods项目管理私有仓库 招 ...

  5. 数据结构(C实现)------- 顺序栈

    栈是限定仅在表的一端进行插入或删除的纯属表,通常称同意插入.删除的一端为栈顶(Top),对应在的.则称还有一端为栈底(Bottom). 不含元素的栈则称为空栈. 所设栈S={a1,a2,a3,..., ...

  6. 深入理解android view 生命周期

    作为自定义 view 的基础,如果不了解Android  view 的生命周期 , 那么你将会在后期的维护中发现这样那样的问题 ....... 做过一段时间android 开发的同学都知道,一般 on ...

  7. CodeForces 754D Fedor and coupons&&CodeForces 822C Hacker, pack your bags!

    D. Fedor and coupons time limit per test 4 seconds memory limit per test 256 megabytes input standar ...

  8. 从map到hash

    https://zybuluo.com/ysner/note/1175387 前言 这两种技巧常用于记录和去重量少而分散的状态. 都体现了映射思想. \(map\) 我一般是数组开不下时拿这玩意判重. ...

  9. nodejs--Nodejs单元测试小结

    前言 最近在写一课程的Project,用Node写了一个实时聊天小应用,其中就用到了单元测试.在写Node单元测试的时候,一方面感受到了单元测试的重要性,另一方面感受到了Node单元测试的不够成熟,尚 ...

  10. MSSQL:查看作业情况

    select j.name 'Job名',        j.description '描述',        j.ENABLED job_enabled,        cast(js.last_r ...