源码:http://git.oschina.net/sancha...

Spark Framework beetl fastjson 结合

项目结构如下

pom.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.coderknock</groupId><artifactId>TestSpark</artifactId><version>1.0-SNAPSHOT</version><properties><log4j_version>1.2.17</log4j_version><slf4j_version>1.7.21</slf4j_version></properties><dependencies><dependency><groupId>com.ibeetl</groupId><artifactId>beetl</artifactId><version>2.4.0</version></dependency><dependency><groupId>com.sparkjava</groupId><artifactId>spark-core</artifactId><version>2.5</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.8.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.12</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${slf4j_version}</version></dependency><dependency><groupId>org.jodd</groupId><artifactId>jodd-http</artifactId><version>3.7.1</version></dependency></dependencies><build><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>2.5.1</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>2.1.1</version><configuration><warName>test</warName></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-dependency-plugin</artifactId><executions><execution><id>install</id><phase>install</phase><goals><goal>sources</goal></goals></execution></executions></plugin></plugins></build>
</project>

WebSocket推送,普通Get请求以及返回Json的请求、使用Beetl进行视图解析的方法:

/*** 拿客 www.coderknock.com* 微信公众号 coderknock* 作者:三产*/import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.HashMap;import static spark.Spark.*;public class Test {private static Logger logger = LoggerFactory.getLogger(Test.class);public static void main(String[] args) {//设置端口port(9090);//EchoWebSocket不能是内部类webSocket("/echo", EchoWebSocket.class);//这个必须有,不然注册不成功init();// matches "GET /hello/foo" and "GET /hello/bar"// request.params(":name") is 'foo' or 'bar'get("/hello/:name", (request, response) -> {//使用Beetl进行视图的解析return Tmpl.render("hello.html", request.params());});// matches "GET /say/hello/to/world"// request.splat()[0] is 'hello' and request.splat()[1] 'world'get("/say/*/to/*", (request, response) -> {response.type("application/json");HashMap<String, Object> map = new HashMap<String, Object>();map.put("1", request.splat()[0]);map.put("2", request.splat()[1]);//打印结果logger.debug("$$$$$$$$$$$$$$$$$" + JSON.toJSON(map).toString());return JSON.toJSON(map);});get("/home", (request, response) -> {return Tmpl.render("index.html");});int i = 0;        //WebSocket主动推送的实现,启动轮询,定时发送消息while (true) {try {Thread.currentThread().sleep(1000);i++;logger.debug("--->" + i);if (i % 5 == 1) {EchoWebSocket.send(i);logger.debug("--->第" + i + "次发送");}} catch (InterruptedException e) {e.printStackTrace();}}}}

WebSocket实现类

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;/*** 拿客 www.coderknock.com* 微信公众号 coderknock* 作者:三产*/
@WebSocket
public class EchoWebSocket {private static Logger logger = LoggerFactory.getLogger(EchoWebSocket.class);// Store sessions if you want to, for example, broadcast a message to all usersprivate static final Queue<Session> sessions = new ConcurrentLinkedQueue<>();@OnWebSocketConnectpublic void connected(Session session) {sessions.add(session);//建立连接的时候logger.debug("新增了Session" + session.toString());}@OnWebSocketClosepublic void closed(Session session, int statusCode, String reason) {sessions.remove(session);//关闭连接或者浏览器关闭时logger.debug("删除了Session" + session.toString());}@OnWebSocketMessagepublic void message(Session session, String message) throws IOException {//获取到客户端发送的消息时,对消息进行输出,病简单处理返回另一个消息System.out.println("Got: " + message);   // Print messagesession.getRemote().sendString(message + "1231"); // and send it back}public static void send(int i) {//这里只是简单的给所有用户推送,其实可以改造一下(将Session与用户id之类的通过发送消息的方式一一对应,这样可以为特定用户进行消息的发送)sessions.forEach(session -> {try {                        session.getRemote().sendString("第" + i + "次主动推送");} catch (Exception e) {logger.error("主动推送失败", e);}});}
}

Beetl的一个简单封装:

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.WebAppResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.HashMap;
import java.util.Map;/*** 拿客 www.coderknock.com* 微信公众号 coderknock* 作者:三产*/
public class Tmpl {private static GroupTemplate gt;private static Logger logger = LoggerFactory.getLogger(Tmpl.class);static {try {Configuration cfg = Configuration.defaultConfiguration();WebAppResourceLoader resourceLoader = new WebAppResourceLoader();gt = new GroupTemplate(resourceLoader, cfg);} catch (Exception e) {e.printStackTrace();}}public static String render(String tmplPath) {Template t = gt.getTemplate(tmplPath);return t.render();}public static String render(String tmplPath, Map<String, String> param) {Template t = gt.getTemplate(tmplPath);Map<String, String> convertMap = new HashMap<>();try {param.forEach((x, y) -> {if (x.startsWith(":")) {convertMap.put(x.substring(1), y);}});} catch (Exception e) {logger.error("转换失败", e);}t.binding(convertMap);return t.render();}
}

Get请求高并发测试:

/*** 拿客 www.coderknock.com* 微信公众号 coderknock* 作者:三产*/import jodd.http.HttpRequest;
import jodd.http.HttpResponse;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;public class TestGet {//大家可以适当加大,但是如果太大可能会导致get请求发送失败,大家有优化建议可以告诉我(客户端问题,并不是Spark处理不了高并发)private static int thread_num = 500;private static int client_num = 500;public static void main(String[] args) {long time = System.currentTimeMillis();ExecutorService exec = Executors.newCachedThreadPool();final Semaphore semp = new Semaphore(thread_num);for (int index = 0; index < client_num; index++) {final int NO = index;Runnable run = new Runnable() {public void run() {try {semp.acquire();System.out.println("------------------|" + NO + "|------------------");HttpResponse response = HttpRequest.get("http://localhost:9090/say/Hello-" + NO + "/to/World" + NO).acceptEncoding("gzip").send();System.out.println(response.unzip());System.out.println("------------------&" + NO + "&------------------");//业务逻辑semp.release();} catch (Exception e) {e.printStackTrace();}}};exec.execute(run);}exec.shutdown();}
}WebSocket可以通过websocket.html测试(建议使用IE8以上浏览器):
![WebSocket测试](http://img.coderknock.com/201606/03214119104_02161833_kTuD.png "WebSocket测试")
先点击“建立连接”,然后可以填写一些内容,点击“发送数据”,连接建立后就开始了主动推送,我设置的是5秒钟一次。

我是广告

本人的直播课程在 7 月份就要开始了,希望小伙伴们支持一下,现在报名有优惠噢

https://segmentfault.com/l/15...

https://segmentfault.com/l/15...

微服务框架 Spark Framework相关推荐

  1. Java微服务框架一览

    原文:Java Microservices: Code Examples, Tutorials, and More 作者:Angela Stringfellow 翻译:雁惊寒 译者注:本文首先简单介绍 ...

  2. 秒杀springboot——未来轻量级高性能的Java云原生微服务框架来啦

    秒杀springboot--未来轻量级高性能的Java云原生微服务框架来啦 引子 自2003年Rod.Juergen 和 Yann开发并发布Spring项目后,J2EE 迎来了新的开始.在 2013 ...

  3. 拥抱.NET 5,从自研微服务框架开始

    " 2016年发布了.NET Core第一个正式版本,而.NET5也将在下个月就正式来临了,技术日新月异,也有点让人应接不暇.在框架设计上,.NET Framework的全家桶理念,培养了一 ...

  4. Java 微服务框架选型(Dubbo 和 Spring Cloud?),大厂 HR 如何面试

    写在最前面,我总结出了很多互联网公司的面试题及答案,并整理成了文档,以及各种学习的进阶学习资料,免费分享给大家.扫码加微信好友进[程序员面试学习交流群],免费领取.也欢迎各位一起在群里探讨技术. 微服 ...

  5. 技术研究院006---B站自用的微服务框架——Kratos

    大家都知道微服务有两个痛点,一个是如何拆分微服务,微服务的边界怎么划分制定:二是微服务上了规模之后如何管理,因为只要上了规模,任何小小的问题都可能会被放大,最后导致雪崩效应. Bilibili作为一个 ...

  6. golang微服务框架对比_最强开源微服务框架,全网独家整理

    诞生于 2014 年的"微服务架构",其思想经由 Martin Fowler 阐述后,在近几年持续受到重视,理论与相关实践都不断发展,目前它已经成为了主流软件架构模式. 关于微服务 ...

  7. Go:十大主流微服务框架

    1.Istio(31.7K) 项目简介:Istio是由Google.IBM和Lyft开源的微服务管理.保护和监控框架.使用istio可以很简单的创建具有负载均衡.服务间认证.监控等功能的服务网络,而不 ...

  8. kratos mysql_kratos微服务框架学习笔记一(kratos-demo)

    本文将为您描述kratos微服务框架学习笔记一(kratos-demo),教程操作步骤: 目录 kratos微服务框架学习笔记一(kratos-demo) kratos本体 demo kratos微服 ...

  9. 【GoLang】go 微服务框架 Web框架学习资料

    参考资料: 通过beego快速创建一个Restful风格API项目及API文档自动化:  http://www.cnblogs.com/huligong1234/p/4707282.html Go 语 ...

最新文章

  1. 微调torchvision 0.3的目标检测模型
  2. JAVA中console方法怎么用_Java中Console对象实例代码
  3. eclipse的怪问题。background indexer crash recovery .java.lang.OutOfMemoryError: Java heap space
  4. win10 自定义分辨率
  5. ITK:颜色归一化相关
  6. Qt Creator分析函数执行
  7. 云南大学网络课程作业计算机,云南大学842计算机程序设计考研复习经验
  8. Visitor(访问者)--对象行为型模式
  9. 百度快照被劫持跳转到博彩页面的解决办法
  10. SQL Server系列
  11. python实现二分查找算法
  12. Ansible 命令
  13. 无人驾驶路径规划(一)全局路径规划 - RRT算法原理及实现
  14. 图卷积神经网络(GCN)相关应用
  15. linux 设置 中文输入法,linux的中文输入法设置
  16. 处理vue项目中使用es6模板字符串中\n换行问题
  17. 风云格式工厂隐私政策
  18. 美国人口与种族变迁史
  19. Spring框架的基本使用
  20. php generator 风雪,PHP 生成器Generator理解

热门文章

  1. Jmeter4.0分布式测试时启动Jmeter.server时报错
  2. 使用 vscode将本地项目上传到github、从github克隆项目以及删除github上的某个文件夹...
  3. Network 第六篇 - 三层交换机配置路由功能
  4. RMAN备份与恢复(三)--备份相关概念
  5. #一周五# VS2015 CTP6, TFS2015 CTP1更新,老衣的开发工具汇总,2015 MVP 社区巡讲...
  6. shell基础——变量定义
  7. JAVA面试题,比较经典的面试题
  8. [Python] Django+Apache 报 [wsgi:error]问题解决
  9. SpringBoot脚手架工程快速搭建
  10. SpringBoot集成Log4j2框架