motan入门环境搭建手记

2016-10-27  本文已影响0人  大鱼bigfish

注意事项:

1.  建议服务提供者使用main函数运行,不要在tomcat中运行(会多占用端口等)
2. 如果一个服务提供者必须是web项目,要部署在tomcat中,则需要在servlet启动后,调用MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);来注册服务优雅起停,测试表示如果不调用,则无法调用到服务,使用motan-manager查看服务,可以看到服务状态是Unavailable Server,如果值设置为false,服务也是不可用的
3. 服务提供者和服务消费者最好是在不同的tomcat中运行,不要运行于同一个tomcat中,原则是如果先运行了服务消费者,则会导致找不到服务方法,导致启动报错
4. 服务消费者的controller中无法直接引用motan服务,需要定义一个Service,然后在Service中引用对应的motan服务,原因应该是Controller与普通spring bean 所处理容器不同

主要过程如下:

一. 新建3个项目,分别是

 motan-api  是对应的api接口
 motan-server 是motan-api的实现,依赖motan-api
 motan-client 调用motan-api的实现,依赖motan-api

二.motan-api是普通的工程,生成jar包,只有一个接口

package motan.demo.api;
public interface IHelloWorld {
     public String hello(String name);
}

三.motan-server是一个web工程,

3.1 pom.xml配置如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>jzweb</groupId>
     <artifactId>motan-server</artifactId>
     <version>0.1</version>
     <packaging>war</packaging>
     <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>
     <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>
          <dependency>
              <groupId>jzweb</groupId>
              <artifactId>motan-api</artifactId>
              <version>0.1</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>
     </dependencies>
     <build>
          <finalName>motan-server</finalName>
          <plugins>
              <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>
</project>
3.2 在src/main/resources中添加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="127.0.0.1:2181" connectTimeout="2000"/>
    <!-- 协议配置。为防止多个业务配置冲突,推荐使用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>
3.3 在src/main/resources目录中添加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>
3.4 从官方拷贝log4j.properties文件到src/main/resources目录
3.5 因为这个一个web工程,要放在tomcat下运行,为了实现优雅的起启服务,需要定义一个ServletContextListener来启动或关闭服务MotanSwitcherUtil,经测试,如果不配置的话,通过servlet发布的服务将无法使用
package motan.demo.server.server.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.weibo.api.motan.common.MotanConstants;
import com.weibo.api.motan.util.MotanSwitcherUtil;

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);
    }

}
     ```
#####3.5  实现类HelloWorldImpl实现api项目中的接口,如下,其中,MotanService是motan的服务注册注解
```java     
package motan.demo.server.api.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.weibo.api.motan.config.springsupport.annotation.MotanService;
import motan.demo.api.IHelloWorld;

@MotanService
public class HelloWorldImpl implements IHelloWorld{

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

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

}
3.6 配置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>
3.7 如果没有controller,不需要启动tomcat服务,可以直接使用main函数启动,类如下:
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...");
     }
}

说明:这个配置过程中
1. zookeeper等信息在spring.xml中配置的
2. rpc实现类采用的是注解的方式

四.motan-client项目,这也是一个web工程

4.1 web.xml配置文件与motan-server项目相同
4.2 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">
     
      <!-- 自动扫描包 ,将带有注解的类 纳入spring容器管理 -->
     <context:annotation-config/>
     <context:component-scan base-package="motan.demo">
     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
     <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
     </context:component-scan>
 
     <context:component-scan base-package="motan.demo"/>
     <motan:annotation package="motan.demo"/>

    <motan:registry regProtocol="zookeeper" name="registry" address="127.0.0.1:2181" connectTimeout="2000"/>
    <!-- motan协议配置 -->
    <motan:protocol default="true" name="motan" haStrategy="failover"
                    loadbalance="roundrobin" maxClientConnection="10" minClientConnection="2"/>
    <!-- 通用referer基础配置 -->
    <motan:basicReferer requestTimeout="200" accessLog="false"
                        retries="2" group="motan-demo-rpc" module="motan-demo-rpc"
                        application="myMotanDemo" protocol="motan" registry="registry"
                        id="motantestClientBasicConfig" throwException="false" check="true"/>
</beans>

4.3 spring-mvc.xml配置文件与server相同(如果没有controller,也可以不用配置)

4.4 定义一个Service,引用motan服务
@Service
public class SayHello {
     @MotanReferer
     private IHelloWorld 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;
     }
}
4.5 定义controller,引用Service
@RestController
public class HelloController {
     @Autowired
     private SayHello hello;
     private Logger log = LoggerFactory.getLogger(getClass());
     @RequestMapping("/hello/{name}")
     @ResponseBody
     public String hello(@PathVariable("name") String name){
          String result = hello.say(name);
          System.out.println(result);
          log.debug(result);
          return result;
     }
}
4.6 如果这个项目也没有controller,则也可以直接使用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);
     }
}
上一篇下一篇

猜你喜欢

热点阅读