Akka是一个高性能,高容错的的分布式框架,并且对Camel也提供了很好的支持,下面创建一个Akka Camel的demo,运行环境:CentOS7 + IntelliJ + JDK8。这个demo分别创建一个Producer和Consumer,实现Redis的pub/sub功能。
 
1,创建Maven工程,加入dependencies,pom.xml文件如下:
 
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-redis</artifactId>
<version>2.17.0</version>
</dependency> <dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-stream</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.11</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-camel_2.11</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
2,分别创建MyRedisProducer和MyRedisConsumer类,这两个类分别继承akka提供的UntypedProducerActor和UntypedConsumerActor,用于产生和消费消息,代码如下:
 
 
/**
* Created by sam on 5/9/16.
*/
public class MyRedisProducer extends UntypedProducerActor { public void preStart() {
super.preStart();
} @Override
public String getEndpointUri() {
return "spring-redis://localhost:9999?connectionFactory=#connectionFactory&serializer=#serializer";
} @Override
public void onRouteResponse(Object message) {
System.out.println("response from route:{}" + message);
} @Override
public Object onTransformOutgoingMessage(Object message) {
if (message instanceof CamelMessage) {
CamelMessage camelMessage = (CamelMessage) message;
return camelMessage;
} else {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("CamelRedis.Command", "PUBLISH");
headers.put("CamelRedis.Channel", "testChannel");
headers.put("CamelRedis.Message", message.toString());
CamelMessage camelMessage = new CamelMessage(message, headers);
return camelMessage;
}
}
}
在MyRedisProducer类中,需要预处理收到的消息,为消息设置headers属性,Camel Redis组件是根据headers属性类执行命令的。
getEndpointUri中用到的connectionFactory和serializer,会在创建actor的时候进行定义。
 

/**
* Created by sam on 5/9/16.
*/
public class MyRedisConsumer extends UntypedConsumerActor { @Override
public String getEndpointUri() {
return "spring-redis://localhost:9999?connectionFactory=#connectionFactory&serializer=#serializer&channels=testChannel&command=SUBSCRIBE";
} @Override
public void onReceive(Object o) throws Exception {
System.out.println(o);
if (o instanceof CamelMessage) {
CamelMessage msg = (CamelMessage) o;
System.out.println(msg.getBodyAs(String.class, getCamelContext()));
}
}
}
MyRedisConsumer会将接收到的消息放在message body中。
 
3,创建Actor,代码如下:
/**
* Created by sam on 5/9/16.
*/
public class RedisTest {
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create("redis-actor");
Camel camel = CamelExtension.get(system); // 获取Camel对象,该对象可以直接操作Camel,比如获取CamelContext对象等。
PropertyPlaceholderDelegateRegistry delegateRegistry = (PropertyPlaceholderDelegateRegistry) camel.context().getRegistry();
JndiRegistry registry = (JndiRegistry) delegateRegistry.getRegistry(); // Apache Camel默认使用JndiRegistry来注册类信息。
if (registry.lookup("connectionFactory") == null && registry.lookup("serializer") == null) {
// 添加beans
JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
connectionFactory.setHostName("localhost");
connectionFactory.setPassword("1234567890");
connectionFactory.setPort(9999);
// call this method to initialize connection factory
connectionFactory.afterPropertiesSet();
registry.bind("connectionFactory", connectionFactory); registry.bind("serializer", new StringRedisSerializer());
} // 创建producer和consumer
ActorRef producer = system.actorOf(Props.create(MyRedisProducer.class), "redisProducer");
ActorRef consumer = system.actorOf(Props.create(MyRedisConsumer.class), "redisConsumer"); while (true) {
Thread.sleep(1000);
producer.tell(new Date().toString(), ActorRef.noSender());
}
}
}
在这段代码中,先获得默认的JndiRegistry对象,并注册connectionFactory和serializer beans,注意使用JndiRegistry时,需要在资源文件中添加jndi.properties文件,内容如下:

java.naming.factory.initial = org.apache.camel.util.jndi.CamelInitialContextFactory
最后使用producer来发送消息,在consumer中,会得到输出,结果如下:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
response from route:{}CamelMessage(null, Map())
CamelMessage(Thu May 12 09:38:04 CST 2016, Map(MessageExchangeId -> ID-localhost-localdomain-33258-1463017082575-0-2, breadcrumbId -> ID-localhost-localdomain-33258-1463017082575-0-1, CamelRedis.Channel -> testChannel, CamelRedis.Pattern -> [B@5910162e))
Thu May 12 09:38:04 CST 2016
response from route:{}CamelMessage(null, Map())
CamelMessage(Thu May 12 09:38:05 CST 2016, Map(MessageExchangeId -> ID-localhost-localdomain-33258-1463017082575-0-4, breadcrumbId -> ID-localhost-localdomain-33258-1463017082575-0-3, CamelRedis.Channel -> testChannel, CamelRedis.Pattern -> [B@4154c5ce))
Thu May 12 09:38:05 CST 2016
response from route:{}CamelMessage(null, Map())
CamelMessage(Thu May 12 09:38:06 CST 2016, Map(MessageExchangeId -> ID-localhost-localdomain-33258-1463017082575-0-6, breadcrumbId -> ID-localhost-localdomain-33258-1463017082575-0-5, CamelRedis.Channel -> testChannel, CamelRedis.Pattern -> [B@2cb03be0))
Thu May 12 09:38:06 CST 2016

Apache Camel系列(4)----Akka Camel的更多相关文章

  1. Apache Shiro系列之五,概述 —— 配置

    Shiro设计的初衷就是可以运行于任何环境:无论是简单的命令行应用程序还是复杂的企业集群应用.由于运行环境的多样性,所以有多种配置机制可用于配置,本节我们将介绍Shiro内核支持的这几种配置机制.   ...

  2. Apache Shiro系列四,概述 —— Shiro的架构

    Shiro的设计目标就是让应用程序的安全管理更简单.更直观.     软件系统一般是基于用户故事来做设计.也就是我们会基于一个客户如何与这个软件系统交互来设计用户界面和服务接口.比如,你可能会说:“如 ...

  3. Apache Shiro系列三,概述 —— 10分钟入门

     一.介绍 看完这个10分钟入门之后,你就知道如何在你的应用程序中引入和使用Shiro.以后你再在自己的应用程序中使用Shiro,也应该可以在10分钟内搞定. 二.概述 关于Shiro的废话就不多说了 ...

  4. apache kafka系列之Producer处理逻辑

     最近研究producer的负载均衡策略,,,,我在librdkafka里边用代码实现了partition 值的轮询方法,,,但是在现场验证时,他的负载均衡不起作用,,,所以来找找原因: 下文是一篇描 ...

  5. Apache Shiro系列一,概述 —— 初识

    一.什么是Shiro Apache Shiro是一个强大.灵活.开源的安全框架,它支持用户认证.权限控制.企业会话管理以及加密等. Apache Shiro的第一个也是最重要的一个目标就是易于使用和理 ...

  6. Apache Phoenix系列 | 从入门到精通(转载)

    原文地址:https://cloud.tencent.com/developer/article/1498057 来源: 云栖社区 作者: 瑾谦 By 大数据技术与架构 文章简介:Phoenix是一个 ...

  7. Apache Shiro系列(1)

    Apache Shiro是啥呢,安全框架. 360百科是这么描述的:        Apache Shiro(日语"堡垒(Castle)"的意思)是一个强大易用的Java安全框架, ...

  8. Apache Shiro系列二,概述 —— 基本概念

    做任何事情,首先要双方就一些概念的理解达成一致,这样大家就有共同语言,后续的沟通效率会高一些. #,Authentication,认证,也就是验证用户的身份,就是确定你是不是你,比如通过用户名.密码的 ...

  9. Apache Commons 系列简介 之 Pool

    一.概述 Apache Commons Pool库提供了一整套用于实现对象池化的API,以及若干种各具特色的对象池实现.2.0版本,并非是对1.x的简单升级,而是一个完全重写的对象池的实现,显著的提升 ...

  10. Apache Shiro系列教程之二:十分钟上手Shiro

    在本教程中,我们会写一个简单的.仅仅输出一些内容命令行程序,从而对Shiro有一个大体的感觉. 一.准备工作 本教程需要Java1.5+,并且我们用Maven生成项目,当然Maven不是必须的,你也可 ...

随机推荐

  1. FastJson漏洞复现

    FastJson漏洞复现 环境:vulhub/fastjson Fastjson是阿里巴巴公司开源的一个高性能的Java库,专门用于处理JSON数据格式. 它不仅能够将Java对象序列化为JSON格式 ...

  2. JVM性能优化, Part 3 —— 垃圾回收

    ImportNew注:本文是JVM性能优化 系列-第3篇-<JVM性能优化, Part 3 -- 垃圾回收> 第一篇 <JVM性能优化, Part 1 ―― JVM简介 > 第 ...

  3. C语言八股文(温故知新)

    1.volatile关键字 volatile int i=10; int j = i; ... int k = i; volatile告诉编译器i变量是随时可能发生变化的,例如IO端口的输入值,所以每 ...

  4. python之DataClass

    Python 在版本 3.7 (PEP 557) 中引入了dataclass.dataclass允许你用更少的代码和更多的开箱即用功能来定义类. 下面定义了一个具有两个实例属性 name 和 age ...

  5. vue3 中屏蔽控制台中的警告信息

    main.js中 const app = Vue.createApp({}); // 屏蔽错误信息 app.config.errorHandler = () => null; // 屏蔽警告信息 ...

  6. Windows 触控笔

    平板以及二合一平板均是触控屏,Laptop现在也有很多屏幕带触控 触控屏,都会配置触控笔配件,目前市场上一般是电容屏+电容笔的技术方案. 触控笔分为主动笔和被动笔,主动笔占绝大部分.主动笔是通过内部电 ...

  7. ChatGPT生成测试用例的最佳实践(四)

    通常情况下还应该进行测试用例外部评审.将已完成的基于百度关键字搜索业务的功能和安全测试用例集的存放位置告知项目团队成员,需要预留出一定的时间,便于项目组研发.产品人员阅读,以免在项目团队测试用例评审会 ...

  8. flutter问题汇总

    Text文字居中 Text(           'You will need to post a photo before you can play!',           textAlign:  ...

  9. TeamViewer 的替代品 ZeroTier + NoMachine

    之前不怎么用 TeamViewer,最近用的多了,特别好用,有点上瘾,在哪儿都能连家里的 RTX,太棒了. 然后它就开始作了. 有没有好的替代方案呢?有人推荐向日葵,向日葵显然是以盈利为目的的我不想再 ...

  10. manim边学边做--移动动画

    在Manim中,其实直线移动的动画非常简单,每个Mobject对象都有animate属性, 通过obj.animate.shift()或者obj.animate.move_to()很容易将对象从一个位 ...