docker+k8s+activemq+.net core 客戶端實現

源碼地址: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:客戶端運行效果

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章