docker+k8s+activemq+.net core 客户端实现

17 篇文章 1 订阅
1 篇文章 0 订阅

源码地址:https://github.com/oopxiajun/docker-activemq-java-.net-core

一,使用docker 容器 部署 ActiveMQ 

1,查找activemq镜像

# docker search activemq
NAME                                     DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
webcenter/activemq                       ActiveMQ 5.14.3 with OpenJDK-jre-8-headless …   173                                     [OK]
rmohr/activemq                           Various versions of ActiveMQ neatly packet i…   117                                     [OK]
vromero/activemq-artemis                 ActiveMQ Artemis image (Debian and Alpine ba…   28                                      [OK]
cloudesire/activemq                      Latest activemq                                 5                                       [OK]
aterreno/activemq-dockerfile                                                             3                                       [OK]
andreptb/activemq                        Debian Jessie based image with ActiveMQ inst…   3                                       [OK]
jtech/activemq                           Latest ActiveMQ production distribution on l…   1                                       [OK]
larrytalley/activemq-docker-deployable   Deployable instance of Apache ActiveMQ insta…   1                                       [OK]
benyoo/activemq                          activemq run in docker                          1                                       [OK]
ddmlu/activemq-openshift                 Fork of ayannah/activemq for openShift          1                                       [OK]
smaject/activemq                         Apache ActiveMQ based on CentOS 7               1                                       [OK]
spacetimeinsight/activemq                activemq                                        1                                       
tremolosecurity/activemq-docker          Hardened version of ActiveMQ for use with Op…   1                                       [OK]
antonw/activemq-jmx                      ActiveMQ with (remote) JMX                      1                                       [OK]
bgbilling/activemq                       Apache ActiveMQ                                 0                                       [OK]
kibiluzbad/activemq-artemis-operator     ActiveMQ Artemis Operator                       0                                       
aomitech/activemq-client                                                                 0                                       
beeyond/activemq                         ActiveMQ MySQL                                  0                                       
albertonavarro/activemq12s                                                               0                                       
aungzy/activemq                          Docker image for ActiveMQ, forked from https…   0                                       [OK]
joakimgreenbird/activemq-bridge          Bridge from kafka to activemq.                  0                                       
duffqiu/activemq-hub                                                                     0                                       [OK]
camptocamp/activemq-mcollective          Activemq image for mcollective                  0                                       [OK]
ayannah/activemq                         Dockerized ActiveMQ                             0                                       [OK]
cloudunit/activemq-5.13                  activemq-5.13                                   0                                       [OK]

2,启动容器

2.2 直接docker run 启动容器

docker run -d --name myactivemq -p 61617:61616 -p 8162:8161 webcenter/activemq

 61616是 activemq 的容器使用端口(映射为61617),8161是 web 页面管理端口(对外映射为8162)

 

2.2 使用docker-compose 启动容器

docker-compose.yaml 文件 内容如下

  # 最简单,无需任何配置,请使用这个下面配置 来启动容器
   version: '2'
     services:
       activemq-test: 
         ports:
           - "8161:8161"
           - "61616:61616"
           - "5672:5672"
           - "61613:61613"
           - "1883:1883"
           - "61614:61614"
         image:  webcenter/activemq:latest

启动

docker-compose -f docker-compose.yaml up  -d

3,扩展配置后启动容器(activemq.xml,jetty.xml,users.properties等)+docker-compose 重新构建镜像 + 启动容器

3.1 添加自定义一些配置项

activemq.xml 中改端口,加访问帐号配置,这里我暂时只做用户授权的改动

<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!-- START SNIPPET: example -->
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <!-- Allows us to use system properties as variables in this configuration file -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:${activemq.conf}/credentials.properties</value>
        </property>
    </bean>

    <!-- Allows accessing the server log -->
    <bean id="logQuery" class="io.fabric8.insight.log.log4j.Log4jLogQuery" lazy-init="false" scope="singleton" init-method="start" destroy-method="stop">
    </bean>

    <!--
        The <broker> element is used to configure the ActiveMQ broker.
    -->
    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}">

        <destinationPolicy>
            <policyMap>
                <policyEntries>
                    <policyEntry topic=">">
                        <!-- The constantPendingMessageLimitStrategy is used to prevent
                         slow topic consumers to block producers and affect other consumers
                         by limiting the number of messages that are retained
                         For more information, see:

                         http://activemq.apache.org/slow-consumer-handling.html

                    -->
                        <pendingMessageLimitStrategy>
                            <constantPendingMessageLimitStrategy limit="1000"/>
                        </pendingMessageLimitStrategy>
                    </policyEntry>
                </policyEntries>
            </policyMap>
        </destinationPolicy>


        <!--
            The managementContext is used to configure how ActiveMQ is exposed in
            JMX. By default, ActiveMQ uses the MBean server that is started by
            the JVM. For more information, see:

            http://activemq.apache.org/jmx.html
        -->
        <managementContext>
            <managementContext createConnector="false"/>
        </managementContext>

        <!--
            Configure message persistence for the broker. The default persistence
            mechanism is the KahaDB store (identified by the kahaDB tag).
            For more information, see:

            http://activemq.apache.org/persistence.html
        -->
        <persistenceAdapter>
            <kahaDB directory="${activemq.data}/kahadb"/>
        </persistenceAdapter>


        <!--
            The systemUsage controls the maximum amount of space the broker will
            use before disabling caching and/or slowing down producers. For more information, see:
            http://activemq.apache.org/producer-flow-control.html
          -->
        <systemUsage>
            <systemUsage>
                <memoryUsage>
                    <memoryUsage percentOfJvmHeap="70" />
                </memoryUsage>
                <storeUsage>
                    <storeUsage limit="100 gb"/>
                </storeUsage>
                <tempUsage>
                    <tempUsage limit="50 gb"/>
                </tempUsage>
            </systemUsage>
        </systemUsage>

        <!--
            The transport connectors expose ActiveMQ over a given protocol to
            clients and other brokers. For more information, see:

            http://activemq.apache.org/configuring-transports.html
        -->
        <transportConnectors>
            <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
        </transportConnectors>

        <!-- destroy the spring context on shutdown to stop jetty -->
        <shutdownHooks>
            <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
        </shutdownHooks>
        <!-- 添加访问ActiveMQ的账号密码 -->
        <plugins>
            <simpleAuthenticationPlugin>
                <users>
                    <authenticationUser username="xiajun" password="1234@abc" groups="users,admins"/>
                </users>
            </simpleAuthenticationPlugin>
        </plugins>
    </broker>

    <!--
        Enable web consoles, REST and Ajax APIs and demos
        The web consoles requires by default login, you can disable this in the jetty.xml file

        Take a look at ${ACTIVEMQ_HOME}/conf/jetty.xml for more details
    -->
    <import resource="jetty.xml"/>

</beans>
<!-- END SNIPPET: example -->

上面内容中 broker 里面加 添加访问ActiveMQ的账号密码 


        <!-- 添加访问ActiveMQ的账号密码 -->
        <plugins>
            <simpleAuthenticationPlugin>
                <users>
                    <authenticationUser username="xiajun" password="1234@abc" groups="users,admins"/>
                </users>
            </simpleAuthenticationPlugin>
        </plugins>

 

jetty.xml 网络应用配置,这里我也暂时没做改动

 <!--
        Licensed to the Apache Software Foundation (ASF) under one or more contributor
        license agreements. See the NOTICE file distributed with this work for additional
        information regarding copyright ownership. The ASF licenses this file to You under
        the Apache License, Version 2.0 (the "License"); you may not use this file except in
        compliance with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or
        agreed to in writing, software distributed under the License is distributed on an
        "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        implied. See the License for the specific language governing permissions and
        limitations under the License.
    -->
    <!--
        An embedded servlet engine for serving up the Admin consoles, REST and Ajax APIs and
        some demos Include this file in your configuration to enable ActiveMQ web components
        e.g. <import resource="jetty.xml"/>
    -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="securityLoginService" class="org.eclipse.jetty.security.HashLoginService">
        <property name="name" value="ActiveMQRealm" />
        <property name="config" value="${activemq.conf}/jetty-realm.properties" />
    </bean>

    <bean id="securityConstraint" class="org.eclipse.jetty.util.security.Constraint">
        <property name="name" value="BASIC" />
        <property name="roles" value="user,admin" />
        <!-- set authenticate=false to disable login -->
        <property name="authenticate" value="true" />
    </bean>
    <bean id="adminSecurityConstraint" class="org.eclipse.jetty.util.security.Constraint">
        <property name="name" value="BASIC" />
        <property name="roles" value="admin" />
         <!-- set authenticate=false to disable login -->
        <property name="authenticate" value="true" />
    </bean>
    <bean id="securityConstraintMapping" class="org.eclipse.jetty.security.ConstraintMapping">
        <property name="constraint" ref="securityConstraint" />
        <property name="pathSpec" value="/api/*,/admin/*,*.jsp" />
    </bean>
    <bean id="adminSecurityConstraintMapping" class="org.eclipse.jetty.security.ConstraintMapping">
        <property name="constraint" ref="adminSecurityConstraint" />
        <property name="pathSpec" value="*.action" />
    </bean>
    
    <bean id="rewriteHandler" class="org.eclipse.jetty.rewrite.handler.RewriteHandler">
        <property name="rules">
            <list>
                <bean id="header" class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
                  <property name="pattern" value="*"/>
                  <property name="name" value="X-FRAME-OPTIONS"/>
                  <property name="value" value="SAMEORIGIN"/>
                </bean>
            </list>
        </property>
    </bean>
    
	<bean id="secHandlerCollection" class="org.eclipse.jetty.server.handler.HandlerCollection">
		<property name="handlers">
			<list>
   	            <ref bean="rewriteHandler"/>
				<bean class="org.eclipse.jetty.webapp.WebAppContext">
					<property name="contextPath" value="/admin" />
					<property name="resourceBase" value="${activemq.home}/webapps/admin" />
					<property name="logUrlOnStart" value="true" />
				</bean>
				<bean class="org.eclipse.jetty.webapp.WebAppContext">
					<property name="contextPath" value="/api" />
					<property name="resourceBase" value="${activemq.home}/webapps/api" />
					<property name="logUrlOnStart" value="true" />
				</bean>
				<bean class="org.eclipse.jetty.server.handler.ResourceHandler">
					<property name="directoriesListed" value="false" />
					<property name="welcomeFiles">
						<list>
							<value>index.html</value>
						</list>
					</property>
					<property name="resourceBase" value="${activemq.home}/webapps/" />
				</bean>
				<bean id="defaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler">
					<property name="serveIcon" value="false" />
				</bean>
			</list>
		</property>
	</bean>    
    <bean id="securityHandler" class="org.eclipse.jetty.security.ConstraintSecurityHandler">
        <property name="loginService" ref="securityLoginService" />
        <property name="authenticator">
            <bean class="org.eclipse.jetty.security.authentication.BasicAuthenticator" />
        </property>
        <property name="constraintMappings">
            <list>
                <ref bean="adminSecurityConstraintMapping" />
                <ref bean="securityConstraintMapping" />
            </list>
        </property>
        <property name="handler" ref="secHandlerCollection" />
    </bean>

    <bean id="contexts" class="org.eclipse.jetty.server.handler.ContextHandlerCollection">
    </bean>

    <bean id="jettyPort" class="org.apache.activemq.web.WebConsolePort" init-method="start">
             <!-- the default port number for the web console -->
        <property name="host" value="0.0.0.0"/>
        <property name="port" value="8161"/>
    </bean>

    <bean id="Server" depends-on="jettyPort" class="org.eclipse.jetty.server.Server"
        destroy-method="stop">

        <property name="handler">
            <bean id="handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
                <property name="handlers">
                    <list>
                        <ref bean="contexts" />
                        <ref bean="securityHandler" />
                    </list>
                </property>
            </bean>
        </property>

    </bean>

    <bean id="invokeConnectors" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    	<property name="targetObject" ref="Server" />
    	<property name="targetMethod" value="setConnectors" />
    	<property name="arguments">
    	<list>
           	<bean id="Connector" class="org.eclipse.jetty.server.ServerConnector">
           		<constructor-arg ref="Server" />
                    <!-- see the jettyPort bean -->
                   <property name="host" value="#{systemProperties['jetty.host']}" />
                   <property name="port" value="#{systemProperties['jetty.port']}" />
               </bean>
                <!--
                    Enable this connector if you wish to use https with web console
                -->
                <!-- bean id="SecureConnector" class="org.eclipse.jetty.server.ServerConnector">
					<constructor-arg ref="Server" />
					<constructor-arg>
						<bean id="handlers" class="org.eclipse.jetty.util.ssl.SslContextFactory">
						
							<property name="keyStorePath" value="${activemq.conf}/broker.ks" />
							<property name="keyStorePassword" value="password" />
						</bean>
					</constructor-arg>
					<property name="port" value="8162" />
				</bean -->
            </list>
    	</property>
    </bean>

	<bean id="configureJetty" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
		<property name="staticMethod" value="org.apache.activemq.web.config.JspConfigurer.configureJetty" />
		<property name="arguments">
			<list>
				<ref bean="Server" />
				<ref bean="secHandlerCollection" />
			</list>
		</property>
	</bean>
    
    <bean id="invokeStart" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" 
    	depends-on="configureJetty, invokeConnectors">
    	<property name="targetObject" ref="Server" />
    	<property name="targetMethod" value="start" />  	
    </bean>
    
    
</beans>

users.properties 修改登录用户、密码、权限,这里我加了我自己的用户名和密码

## ---------------------------------------------------------------------------
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements.  See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License.  You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ---------------------------------------------------------------------------

# Defines users that can access the web (console, demo, etc.)
# username: password [,rolename ...]

##值得注意的是 用户名和密码的格式是
##用户名 : 密码 ,角色名
#admin: admin, admin
xiajun:1234@abc,admin


users.properties 里面配置时需要注意格式

3.2 编写Dockerfile文件和run.sh文件

 Dockerfile文件内容如下

FROM  webcenter/activemq:latest
COPY activemq.xml /opt/activemq/conf/activemq.xml
COPY jetty.xml /opt/activemq/conf/jetty.xml
COPY users.properties /opt/activemq/conf/users.properties
COPY run.sh /opt/activemq/bin/run.sh
RUN chmod 777 /opt/activemq/bin/run.sh
# Expose all port 暴露所有用到的端口
EXPOSE 8161
EXPOSE 61616
EXPOSE 5672
EXPOSE 61613
EXPOSE 1883
EXPOSE 61614
# 初始化 
WORKDIR  /opt/activemq/bin/
RUN  ./run.sh 

run.sh文件内容如下

/opt/activemq/bin/activemq start

3.3 编写需要重新构建的docker-compose.yaml

version: '2'
services:
  activemq-test: 
    build:          #镜像构建
      context:  .   #构建镜像时所在的资源路径
      dockerfile: Dockerfile    #构建镜像时需要的dockerfile文件路径
    ports:
      - "8161:8161"
      - "61616:61616"
      - "5672:5672"
      - "61613:61613"
      - "1883:1883"
      - "61614:61614"
    image: activemq-test:v1
    #开机就要启动(请确保docker服务是否设置为开机启动)
    restart: always
    #将数据和日志挂载出来,以防容器重启后数据丢失
    volumes: 
      - "/data/activemq:/data/activemq"
      - "/var/log/activemq:/var/log/activemq"

3.4 启动我们自己配置的镜像容器

#启动
docker-compose -f docker-compose.yaml up --build -d
#停止
docker-compose -f docker-compose.yaml down
docker-compose -f docker-compose.yaml up --build -d
Creating network "docker-activemq_default" with the default driver
Building activemq-test
Step 1/14 : FROM  webcenter/activemq:latest
 ---> 3af156432993
Step 2/14 : COPY activemq.xml /opt/activemq/conf/activemq.xml
 ---> Using cache
 ---> 7cc580890aa4
Step 3/14 : COPY jetty.xml /opt/activemq/conf/jetty.xml
 ---> Using cache
 ---> 5ea0612e0e27
Step 4/14 : COPY users.properties /opt/activemq/conf/users.properties
 ---> Using cache
 ---> 2d32b93f968a
Step 5/14 : COPY run.sh /opt/activemq/bin/run.sh
 ---> Using cache
 ---> e834f97dd320
Step 6/14 : RUN chmod 777 /opt/activemq/bin/run.sh
 ---> Using cache
 ---> 3d424a4e6f46
Step 7/14 : EXPOSE 8161
 ---> Using cache
 ---> 077c3f6d50dc
Step 8/14 : EXPOSE 61616
 ---> Using cache
 ---> a55ad73e523f
Step 9/14 : EXPOSE 5672
 ---> Using cache
 ---> 73d36b246822
Step 10/14 : EXPOSE 61613
 ---> Using cache
 ---> 3b7e5e44d69d
Step 11/14 : EXPOSE 1883
 ---> Using cache
 ---> 164a5819a995
Step 12/14 : EXPOSE 61614
 ---> Using cache
 ---> 359cfb558730
Step 13/14 : WORKDIR  /opt/activemq/bin/
 ---> Using cache
 ---> 9bbddb196563
Step 14/14 : RUN  ./run.sh
 ---> Using cache
 ---> a6beaf349164
Successfully built a6beaf349164
Successfully tagged activemq-test:v1
Creating docker-activemq_activemq-test_1 ... done

[root@master docker-activemq]# docker images
REPOSITORY                                                        TAG                         IMAGE ID            CREATED             SIZE
activemq-test                                                     v1                          a6beaf349164        3 days ago          422MB

[root@master docker-activemq]# docker ps
CONTAINER ID        IMAGE                                               COMMAND                  CREATED              STATUS              PORTS                                                                                                                                    NAMES
defff7c57397        activemq-test:v1                                    "/app/run.sh"            About a minute ago   Up About a minute   0.0.0.0:1883->1883/tcp, 0.0.0.0:5672->5672/tcp, 0.0.0.0:8161->8161/tcp, 0.0.0.0:61613-61614->61613-61614/tcp, 0.0.0.0:61616->61616/tcp   docker-activemq_activemq-test_1

 

通过以上步骤,我们可以同过 http://主机ip:8161/访问ActiveMQ

二,使用Kubernetes 部署ActiveMQ

1:安装k8s 请参考:


 《Kubernetes 安装(基础)》

《K8s 集群(Kubernetes 集群)》

《K8s - 让Master也能当作Node使用的方法》

Kubernetes:应用部署、应用了解、应用公布、应用伸缩,-image=ikubernetes/myapp:v1

 

2:编写k8s部署时需要的 yaml

#部署
---
apiVersion: apps/v1
kind: Deployment                            #对应的类型(可以有Pod、Server、Deployment)
metadata:                                   #原数据类型
  name: activemq-test                    #名称(自定义)
  namespace: default                        #空间名称    
  labels:
    name: activemq-test 
spec:                                       #细则
  replicas: 1                               #镜像副本数量(可以有多少个pod) 
  selector: 
    matchLabels:
      app: activemq-test
  template:  
    metadata:
      labels:
        app: activemq-test               #模版
    spec:                                   #模版细则
      containers:                           #容器列表        
        - name: activemq-test            #镜像名称
          image: webcenter/activemq:latest  #所需镜像(这里可以使用我们上面自己构建的镜像activemq-test:v1)
          ports:                            #端口列表
            - containerPort: 8161           #activemq 网页管理端端口  http访问          
            - containerPort: 61616          #tcp用于客户端连接时使用的端口
          #restart: always                   #容器重启方式
          volumeMounts:                     #挂载数据卷(数据文件和日志文件)
            - mountPath: /data/activemq     #容器内路径
              name: data                    # 要与 volume 中 name 匹配
            - mountPath: /var/log/activemq  #容器内路径
              name: log                     # 要与 volume 中 name 匹配
      volumes:
        - name: data
          hostPath:
            path: /data/activemq     # 使用 pod 所在节点的路径
        - name: log
          hostPath:
            path: /var/log/activemq     # 使用 pod 所在节点的路径
 
#服务
---
apiVersion: v1  #版本
kind: Service    #服务
metadata:
  name: activemq-test-server                    #名称(自定义)
  #namespace: default                        #名称空间
  labels:
    name: activemq-test 
spec:
  #nodeName: master.oopxiajun.com #192.168.134.139
  ports:        #服务需要公布的端口
    - name: admin
      port: 8161        #服务对外的可以访问的端口
      targetPort: 8161  #容器暴露端口     
      protocol: TCP     #HTTP访问 
      nodePort: 8161    #节点端口
    - name: tcp
      port: 61616        #服务对外的可以访问的端口
      targetPort: 61616  #容器端口   
      protocol: TCP      #TCP访问   
      nodePort: 61616    #节点端口
  selector:
    #name: activemq-test   
    #run: activemq-test         
    app: activemq-test #这里选择器一定要选择容器的标签,之前写name:activemq-test和run: activemq-test 都是错的。
  #externalTrafficPolicy: Cluster
  type: NodePort        #通信方式采用节点端口类型
    
# #入口
# ---
# apiVersion: extensions/v1beta1      
# kind: Ingress
# metadata:
#   name: activemq-test
#   namespace: default  
#   labels:
#     name: activemq-test 
# spec:
#   rules:
#   - host: activemq-test-admin.k8s-ingress.com
#     http:
#       paths:
#       - path: /
#         backend:
#           serviceName: activemq-test
#           servicePort: 30000
  
#   - host: activemq-test-server.k8s-ingress.com
#     http:
#       paths:
#       - path: /
#         backend:
#           serviceName: activemq-test
#           servicePort: 30001


 

 

如果需要制定到某台服务器,配置Service中的nodeName 就行,主机名和主机ip都可以。

3:启动、查看(pod、deployment、svc、ep)、停止

[root@master docker-activemq]# kubectl apply -f k8s-activemq-test.yaml 
deployment.apps/activemq-test created
service/activemq-test-server created
[root@master docker-activemq]# kubectl get pod
NAME                            READY   STATUS    RESTARTS   AGE
activemq-test-fd64ccd6c-8nmlm   1/1     Running   0          13s
my-test-ngx-77d994d88-f99lf     1/1     Running   20         40d
myapp-test-cc8865788-6s9xh      1/1     Running   20         40d
myapp-test-cc8865788-dw6nc      1/1     Running   20         40d
myapp-test-cc8865788-xw2mw      1/1     Running   20         40d
[root@master docker-activemq]# kubectl get deployment
NAME            READY   UP-TO-DATE   AVAILABLE   AGE
activemq-test   1/1     1            1           26s
my-test-ngx     1/1     1            1           40d
myapp-test      3/3     3            3           40d
[root@master docker-activemq]# kubectl get svc
NAME                   TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                         AGE
activemq-test-server   NodePort    10.96.232.7      <none>        8161:8161/TCP,61616:61616/TCP   41s
kubernetes             ClusterIP   10.96.0.1        <none>        443/TCP                         41d
my-test-ngx            ClusterIP   10.98.25.92      <none>        80/TCP                          40d
myapp-test             ClusterIP   10.111.200.105   <none>        80/TCP                          40d
[root@master docker-activemq]# kubectl get ep
NAME                   ENDPOINTS                                         AGE
activemq-test-server   10.244.0.162:61616,10.244.0.162:8161              48s
kubernetes             192.168.134.139:6443                              41d
my-test-ngx            10.244.0.141:80                                   40d
myapp-test             10.244.0.136:80,10.244.0.137:80,10.244.0.140:80   40d
[root@master docker-activemq]# kubectl delete -f k8s-activemq-test.yaml 
deployment.apps "activemq-test" deleted
service "activemq-test-server" deleted

在宿主机上可以访问下8161端口

curl localhost:8161
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
  
  http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
 
 
 
 
 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
    <title>Apache ActiveMQ</title> 
    <style type="text/css" media="screen"> 
        @import url(/styles/sorttable.css);
        @import url(/styles/type-settings.css);
        @import url(/styles/site.css);
        @import url(/styles/prettify.css);
    </style> 
</head> 
.......省略无数

 

三,.net core 客户端链接ActiveMQ

我们要引入nugget包: Apache.NMS.ActiveMQ.NetCore

 

1:生产者

using System;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.Util;
namespace ActiveMQ_Producer
{
    class Program
    {
        static string connString = "activemq:tcp://192.168.134.139:61616";
        static string user = "xiajun";
        static string pwd = "1234@abc";
        static string queueName = "xiajun_test_queueName";
        static string topicName = "xiajun_test_topicName";

        static void Main(string[] args)
        {
            TestTopic();
        }
        /// <summary>
        /// 测试主题
        /// </summary>
        static void TestTopic()
        {

            Console.Title = "主题--生产者1";


            //生产者
            var __uri = new Uri(string.Concat(connString));
            IConnectionFactory _factory = new ConnectionFactory(__uri);
            using (IConnection _conn = _factory.CreateConnection(user, pwd))
            {
                using (ISession _session = _conn.CreateSession())
                {
                    IDestination _destination = SessionUtil.GetTopic(_session, topicName);
                    using (IMessageProducer producer = _session.CreateProducer(_destination))
                    {
                        //可以写入字符串,也可以是一个xml字符串等
                        while (true)
                        {
                            Console.WriteLine("请输入主题内容:");
                            string context = Console.ReadLine();
                            ITextMessage request = _session.CreateTextMessage(context);
                            producer.Send(request);
                            Console.WriteLine("发送新新主题:" + context);
                            System.Threading.Thread.Sleep(200);

                        }
                    }
                }
            }
        }

        /// <summary>
        /// 测试队列
        /// </summary>
        static void TestQueue()
        {
            Console.Title = "队列--生产者1";


            //生产者
            var __uri = new Uri(string.Concat(connString));
            IConnectionFactory _factory = new ConnectionFactory(__uri);
            using (IConnection _conn = _factory.CreateConnection(user, pwd))
            {
                using (ISession _session = _conn.CreateSession())
                {
                    IDestination _destination = SessionUtil.GetQueue(_session, queueName);
                    using (IMessageProducer producer = _session.CreateProducer(_destination))
                    {
                        //可以写入字符串,也可以是一个xml字符串等
                        while (true)
                        {
                            Console.WriteLine("请输入队列内容:");
                            string context = Console.ReadLine();
                            ITextMessage request = _session.CreateTextMessage(context);
                            producer.Send(request);
                            Console.WriteLine("发送新新队列信息:" + context);
                            System.Threading.Thread.Sleep(200);

                        }
                    }
                }
            }
        }
    }
}

2:消费者

using System;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.Util;
namespace ActiveMQ_Consumer
{
    class Program
    {
        static string connString = "activemq:tcp://192.168.134.139:61616";
        static string user = "xiajun";
        static string pwd = "1234@abc";
        static string queueName = "xiajun_test_queueName";
        static string topicName = "xiajun_test_topicName";
        static void Main(string[] args)
        {
            TestTopic();
        }


        /// <summary>
        /// 队列测试
        /// </summary>
        /// <param name="args"></param>
        static void TestTopic()
        {
            Console.Title = "主题--消费者1";

            //消费者
            System.Threading.Tasks.Task.Run(() =>
            {
                Uri _uri = new Uri(String.Concat(connString));
                IConnectionFactory factory = new ConnectionFactory(_uri);
                using (IConnection conn = factory.CreateConnection(user, pwd))
                {
                    using (ISession session = conn.CreateSession())
                    {
                        conn.Start();
                        IDestination destination = SessionUtil.GetTopic(session, topicName);
                        using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        {
                            consumer.Listener += (IMessage message) =>
                            {
                                ITextMessage msg = (ITextMessage)message;
                                Console.WriteLine("接收消息:" + msg.Text);
                            };
                            Console.ReadLine();
                        }
                    }
                }
            });

            Console.ReadLine();

        }

        /// <summary>
        /// 队列测试
        /// </summary>
        /// <param name="args"></param>
        static void TestQueue()
        {
            Console.Title = "队列--消费者2";

            //消费者
            System.Threading.Tasks.Task.Run(() =>
            {
                Uri _uri = new Uri(String.Concat(connString));
                IConnectionFactory factory = new ConnectionFactory(_uri);
                using (IConnection conn = factory.CreateConnection(user, pwd))
                {
                    using (ISession session = conn.CreateSession())
                    {
                        conn.Start();
                        IDestination destination = SessionUtil.GetQueue(session, queueName);
                        using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        {
                            consumer.Listener += (IMessage message) =>
                            {
                                ITextMessage msg = (ITextMessage)message;
                                Console.WriteLine("接收消息:" + msg.Text);
                            };
                            Console.ReadLine();
                        }
                    }
                }
            });

            Console.ReadLine();

        }
    }
}

这里我写了两个生产者和消费者,详细代码见GitHub

3:客户端运行效果

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值