spring+motan+zookeeper入門

mdzzdrream發表於2018-03-29

一、vm centos中安裝zookeeper 

在zookeeper根目錄新建data logs資料夾

新建並配置zoo.cfg 

tickTime=2000
dataDir=/software/zookeeper-3.4.11/data
dataLogDir=/software/zookeeper-3.4.11/logs
clientPort=2181
initLimit=5
syncLimit=2

切換到bin目錄# ./zkServer.sh start啟動zookeeper  再# ./zkServer.sh status 檢視是否啟動成功 

二、

idea新建maven專案 選擇webapp


完成後new module 同樣選中webapp 依賴


一個專案中的多個模組。

pom新增spring和motan依賴

<?xml version="1.0" encoding="UTF-8"?>

<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>

    <name>motan-server</name>
    <groupId>motan.demo.server</groupId>
    <artifactId>motan-server</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.jdk>1.7</project.build.jdk>
        <motan.version>0.2.1</motan.version>
        <spring.version>4.3.3.RELEASE</spring.version>
    </properties>


    <build>
        <finalName>motan-server</finalName>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.7</version>
                <configuration>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>8888</port>
                            <maxIdleTime>30000</maxIdleTime>
                        </connector>
                    </connectors>
                    <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
                    <contextPath>/</contextPath>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${project.build.jdk}</source>
                    <target>${project.build.jdk}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <!-- maven生成war包外掛,過濾掉不需要生成到war包中的目錄與檔案 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>      
        <!-- motan -->
        <dependency>
            <groupId>com.weibo</groupId>
            <artifactId>motan-core</artifactId>
            <version>${motan.version}</version>
        </dependency>
        <dependency>
            <groupId>com.weibo</groupId>
            <artifactId>motan-springsupport</artifactId>
            <version>${motan.version}</version>
        </dependency>
        <dependency>
            <groupId>com.weibo</groupId>
            <artifactId>motan-transport-netty</artifactId>
            <version>${motan.version}</version>
        </dependency>
        <dependency>
            <groupId>com.weibo</groupId>
            <artifactId>motan-registry-consul</artifactId>
            <version>${motan.version}</version>
        </dependency>
        <dependency>
            <groupId>com.weibo</groupId>
            <artifactId>motan-registry-zookeeper</artifactId>
            <version>${motan.version}</version>
        </dependency>
        <dependency>
            <groupId>com.weibo</groupId>
            <artifactId>motan-protocol-yar</artifactId>
            <version>${motan.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.3</version>
        </dependency>

        <dependency>
            <artifactId>slf4j-api</artifactId>
            <groupId>org.slf4j</groupId>
            <version>1.7.11</version>
        </dependency>
        <dependency>
            <artifactId>slf4j-log4j12</artifactId>
            <groupId>org.slf4j</groupId>
            <version>1.7.11</version>
        </dependency>
        
        <!-- spring web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.3.0.Final</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.dream</groupId>
            <artifactId>motan-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

>>>>>api模組中新建介面

public interface HelloWorld
{
    public String hello(String name);
}

>>>>>service模組中spring.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:motan="http://api.weibo.com/schema/motan"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://api.weibo.com/schema/motan http://api.weibo.com/schema/motan.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:component-scan base-package="motan.demo"/>
    <motan:annotation package="motan.demo"/>

    <motan:registry regProtocol="zookeeper" name="registry" address="192.168.94.128:2181" connectTimeout="100000"/>
    <!-- 協議配置。為防止多個業務配置衝突,推薦使用id表示具體協議。-->
    <motan:protocol id="demoMotan" default="true" name="motan"
                    maxServerConnection="80000" maxContentLength="1048576"
                    maxWorkerThread="800" minWorkerThread="20"/>
    <!-- 通用配置,多個rpc服務使用相同的基礎配置. group和module定義具體的服務池。export格式為“protocol id:提供服務的埠”-->
    <motan:basicService export="demoMotan:8002"
                        group="motan-demo-rpc" accessLog="false" shareChannel="true" module="motan-demo-rpc"
                        application="myMotanDemo" registry="registry" id="serviceBasicConfig"/>
</beans>

spring-mvc.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd ">

    <!-- 指定自己定義的validator -->
    <!--<mvc:annotation-driven validator="validator"/>-->
    <context:component-scan base-package="motan.demo" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
    <mvc:default-servlet-handler/>

</beans>

api介面實現類

@MotanService
public class HelloWorldImpl implements HelloWorld
{

    private Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public String hello(String name) {
        log.debug("hello,name");
        return "hello,"+name;
    }

}

motan優雅啟動(什麼鬼我也不知道  別人那看來的)

public class MotanServletContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        //這個時候spring已經初始化完成,呼叫以下的類來調整motan狀態
        MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
    }

}

main方法  用作測試 省去寫controller麻煩

public class Main
{
    public static void main(String[] args)
    {
        @SuppressWarnings("unused")
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                new String[] {"classpath*:spring.xml"});
        MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>server start...");
    }
}

忘了web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
  <!-- Spring -->
  <!-- 配置Spring配置檔案路徑 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring.xml</param-value>
  </context-param>
  <!-- 配置Spring上下文監聽器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- Spring -->
  <!-- 配置Spring字元編碼過濾器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- Spring MVC 核心控制器 DispatcherServlet 配置 -->
  <servlet>
    <servlet-name>spring_mvc_dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring_mvc_dispatcher</servlet-name>
    <!-- 攔截所有/* 的請求,交給DispatcherServlet處理,效能最好 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- motan優雅起停功能 -->
  <listener>
    <listener-class>motan.demo.server.listener.MotanServletContextListener</listener-class>
  </listener>
</web-app>

>>>>>client模組

service

@Service
public class SayHello
{
    @MotanReferer
    private HelloWorld hello;
    private Logger log = LoggerFactory.getLogger(getClass());
    public String say(String name){
        String result = hello.hello(name);
        System.out.println(result);
        log.debug(result);
        return result;
    }

}

main

public class Main
{
    public static void main(String[] args) throws InterruptedException {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"classpath:spring.xml" });
        SayHello service = (SayHello) ctx.getBean(SayHello.class);
        for (int i = 0; i < 10; i++) {
            service.say("motan" + i);
            Thread.sleep(1000);
        }
        System.out.println(">>>>>>>>>>>motan demo is finish.");
        System.exit(0);
    }
}

別忘了修改zookeeper地址。

啟動發現失敗 不能註冊zookeeper

centos中關閉防火牆 #systemctl stop firewalld.service

新增log4j發現報錯資訊:session xxxx

首先檢查zookeeper是否啟動成功 ,然後修改連線退出時間在spring.xml中

<motan:registry regProtocol="zookeeper" name="registry" address="192.168.94.128:2181" connectTimeout="2000"/>

如果數值較小 則修改為100000

同時修改zookeeper中zoo.cfg引數 設定minSessionTimeout 和maxSessionTimeout 為100000和200000 

重啟服務,重啟專案。

啟動成功!!



貼一下本人學習原地址  

https://www.jianshu.com/p/575efd2fa74e