springmvc+dubbo+zookeeper

笔者这里使用的是apache-tomcat-6.0.43,jdk1.6,dubbo-admin-2.5.4.war,zookeeper-3.4.6.tar.gz

下面先来介绍安装zookeeper:
解压zookeeper-3.4.6.tar.gz到指定目录,进入zookeeper-3.4.6\conf目录并复制zoo_sample.cfg文件改名为zoo.cfg,因为zookeeper启动时默认找zoo.cfg这个文件,修改zoo.cfg文件内容如下:
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
dataDir=D:\zookeeper-3.4.6\zookeeperinstall\data
# the port at which the clients will connect
clientPort=2181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the 
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1

到此zookeeper安装完毕,进入zookeeper-3.4.6\bin目录,执行zkServer.cmd或者zkServer.sh脚本就可以启动zookeeper了,例如在Windows下进入cmd命令行,D:\zookeeper-3.4.6\bin>zkServer.cmd  这里直接回车即可。


安装dubbo-admin-2.5.4.war管理控制台:
把apache-tomcat-6.0.43/webapps/ROOT目录中的所有内容全部删除掉,把dubbo-admin-2.5.4.war文件解压并把全部内容拷贝到apache-tomcat-6.0.43/webapps/ROOT目录下,如下图

修改WEB-INF目录下的dubbo.properties文件:
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.admin.root.password=root
dubbo.admin.guest.password=guest
启动tomcat
访问http://127.0.0.1:8080/governance/applications/
登录的用户名和密码都是root,不是root/guest

到此为止dubbo-admin-2.5.4.war管理控制台安装完毕。


下面编写服务提供者代码:

applicationCustomer.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:dubbo="http://code.alibabatech.com/schema/dubbo"  
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd  
    http://code.alibabatech.com/schema/dubbo  
    http://code.alibabatech.com/schema/dubbo/dubbo.xsd "> 
  <!-- 具体的实现bean -->  
  <bean id="demoService" class="com.shihuan.zooshare.service.impl.CustomerServiceImpl" />  
  <!-- 提供方应用信息,用于计算依赖关系 -->  
  <dubbo:application name="shihuan_customer"  />	
  <!-- 使用multicast广播注册中心暴露服务地址   
  <dubbo:registry address="multicast://localhost:1234" />-->   
  <!-- 使用zookeeper注册中心暴露服务地址 -->  
  <dubbo:registry address="zookeeper://127.0.0.1:2181" />	 
  <!-- 用dubbo协议在20880端口暴露服务 -->  
  <dubbo:protocol name="dubbo" port="20880" />  
  <!-- 声明需要暴露的服务接口 -->  
  <dubbo:service interface="com.shihuan.zooshare.service.CustomerService" ref="demoService" />
</beans>

CustomerService.java文件代码如下:
package com.shihuan.zooshare.service;

public interface CustomerService {
	public String getName();
}

CustomerServiceImpl.java代码如下:
package com.shihuan.zooshare.service.impl;

import com.shihuan.zooshare.service.CustomerService;

public class CustomerServiceImpl implements CustomerService {

	@Override
	public String getName() {
		System.out.print("shihuan print !!!");
	    return "print result !!!";
	}

}

DubooCustomer.java文件代码如下:
package com.shihuan.zooshare.main;

import java.io.IOException;

import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DubooCustomer {

	public static void main(String[] args) {
		try {
			ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationCustomer.xml"});
			context.start();  
			System.out.println("Press any key to exit.");
			
			System.in.read();
		} catch (BeansException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}

}

build.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<project name="zooshare" default="genericjar" basedir=".">
<property name="src" value="${basedir}/src"/>
<property name="classes" value="${basedir}/bin"/>
<property name="dest" value="${basedir}/dist"/>
<property name="zooshare" value="zooshare.jar"/>
<property name="mainclass" value="com.shihuan.zooshare.main.DubooCustomer" />
	
	<path id="lib-classpath">  
	        <fileset dir="${basedir}/lib">  
	            <include name="**/*.jar"/>     
	            <exclude name="**/*.bak"/>  
	        </fileset>  
	    </path>
	
	<target name="clean">  
	        <delete dir="${basedir}/bin" />  
	        <delete dir="${basedir}/dist" />  
	    </target>
	
<target name="init">
   <mkdir dir="${dest}"/>
</target>
<target name="compile" depends="init">
   <javac encoding="utf-8" srcdir="${src}" destdir="${dest}" includeantruntime="false" source="1.6" debug="yes" verbose="yes" failonerror="true" optimize="false">
   		<compilerarg line="-encoding UTF-8"/>     
   	    <classpath refid="lib-classpath" />
   </javac>
	<copy todir="${classes}">      
	            <fileset dir="${src}">      
	                <include name="**/*.properties"/>  
	                <include name="**/*.xml"/>  
	                <exclude name="**/*.bak"/>    
	            </fileset>      
	        </copy>
</target>	
	
	<target name="antjar" depends="compile">  
	        <!--Create a property containing all .jar files,    
	        prefix lib/, and seperated with a space-->    
	        <pathconvert property="mf.classpath" pathsep=" ">    
	            <mapper>    
	                <chainedmapper>    
	                    <!-- jar包文件只留文件名,去掉目录信息 -->    
	                    <flattenmapper/>    
	                    <!-- add lib/ prefix -->    
	                    <globmapper from="*" to="lib/*"/>    
	                </chainedmapper>    
	            </mapper>   
	            <path refid="lib-classpath"/>  
	        </pathconvert>  
	        <jar destfile="${dest}/zooshare.jar" basedir="${classes}">    
	            <manifest>    
	                <attribute name="Main-class" value="${mainclass}"/>    
	                <attribute name="Class-Path" value="${mf.classpath}"/>    
	            </manifest>    
	        </jar>  
		
	    </target> 
	
	<target name="genericjar" depends="antjar"></target>
</project>


zooshare.jar服务的结构如下图所示:


startZooshare.bat文件内容如下:
@echo off
set CURR_DIR=D:\AppDynamics\dubbo+zookeeper\zooshare
cd /D %CURR_DIR%

set JAVA_HOME=D:\Java\jdk1.6.0_45

set PATH=%JAVA_HOME%\bin;%PATH%

rem 设置变量为延迟加载
setlocal=EnableDelayedExpansion
set CLASSPATH=.;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
for %%j in (lib\*.jar) DO (
    echo %%j
    set CLASSPATH=!CLASSPATH!;%CURR_DIR%\%%j
    echo %CLASSPATH%
)
echo "#############################################"
echo %CLASSPATH%
echo "#############################################"

rem set JVM_ARGS="-Xms:512m -XX:MinPermSize=128m"
rem echo JVM_ARGS=$JVM_ARGS

@echo on
java -cp %CLASSPATH%;zooshare.jar com.shihuan.zooshare.main.DubooCustomer

startZooshare.sh文件内容如下:
#!/bin/sh

export CURR_DIR=/home/zoodubbo/
cd $CURR_DIR
export JAVA_HOME=/usr/java/jdk1.6.0_45
#echo JAVA_HOME=$JAVA_HOME

export PATH=$JAVA_HOME/bin:$PATH
#echo PATH=$PATH

java -version

export CLASSPATH=$CURR_DIR/lib:$CURR_DIR:$JAVA_HOME/lib:$JAVA_HOME/jre/lib

for jarfile in `ls $CURR_DIR/lib/*.jar`
do
 export CLASSPATH=$CLASSPATH:$jarfile
done

#echo CLASSPATH=$CLASSPATH
JVM_ARGS="-Xms:512m -XX:MinPermSize=128m"
echo JVM_ARGS=$JVM_ARGS
ulimit -n 400000
echo "" > nohup.out
#java org.jboss.netty.bootstrap.Bootstrap
nohup $JAVA_HOME/bin/java -cp $CLASSPATH:zoodubbo-0.0.1.jar com.shihuan.zoodubbo.C3p0TestMysql &


在Windows环境中运行cmd窗口执行startZooshare.bat就可以启动zooshare服务了。


下面来介绍服务消费者代码:
dubooweb工程所需要的jar文件截图( 这里要把zooshare.jar加进来)


dubooweb工程总体结构图

jdbc-context.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"  
    xsi:schemaLocation="   
          http://www.springframework.org/schema/beans   
          http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
          http://www.springframework.org/schema/context   
          http://www.springframework.org/schema/context/spring-context-3.1.xsd" default-autowire="byName">

     <context:property-placeholder location="classpath:*.properties"/>
     
     <!-- 自动扫描组件,需要把controller去掉,否则影响事务管理 -->
     <context:component-scan base-package="com.shihuan.web">
     	<context:exclude-filter type="regex" expression="com.shihuan.web.*"/>
     </context:component-scan>
     
</beans>

springmvc-servlet.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:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="   
           http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd   
           http://www.springframework.org/schema/context   
           http://www.springframework.org/schema/context/spring-context-3.1.xsd  
           http://www.springframework.org/schema/mvc   
           http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
           http://www.springframework.org/schema/util 
           http://www.springframework.org/schema/util/spring-util-3.1.xsd">
    
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    	<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
    </bean>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <util:list id="beanList">
                <ref bean="mappingJacksonHttpMessageConverter" />
            </util:list>
        </property>
    </bean>
           
    
    <!-- 启动扫描所有的controller -->
    <context:component-scan base-package="com.shihuan.web"/>
    
    <!--  主要作用于@Controller,激活该模式
        
    	下面是一种简写形式,完全可以手动配置替代这种简写形式;
    	 它会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,
    	   是spring MVC为@Controllers分发请求所必须的
     -->
    <mvc:annotation-driven/>
      
    <!-- 这里拦截器还有一种配置方法【针对路径进行配置】 推荐使用这个,方便直观-->
    <mvc:interceptors>
    	<mvc:interceptor>
    		<mvc:mapping path="/*"/>
			<bean class="com.shihuan.web.interceptor.DubboWebInterceptor"></bean>
    	</mvc:interceptor>
    </mvc:interceptors>
    
     <!-- 全局配置 
    <mvc:interceptors>
    	<bean class="com.olm.website.server.web.interceptor.MyInterceptor"></bean>
    </mvc:interceptors>
    -->
    <!-- 配置js,css等静态文件直接映射到对应的文件夹,不被DispatcherServlet处理 -->
    <mvc:resources location="/resources/**" mapping="/resources"/>
    
    <!-- jsp页面解析器,当Controller返回XXX字符串时,先通过拦截器,然后该类就会在/WEB-INF/views/目录下,查找XXX.jsp文件-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      		<property name="prefix" value="/"></property>
            <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

applicationConsumer.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:dubbo="http://code.alibabatech.com/schema/dubbo"  
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd  
    http://code.alibabatech.com/schema/dubbo  
    http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">		
  <!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->  
  <dubbo:application name="consumer-of-shihuan-app" />	 
    <!-- 使用multicast广播注册中心暴露发现服务地址 -->  
  <dubbo:registry  protocol="zookeeper" address="zookeeper://127.0.0.1:2181" />	   
    <!-- 生成远程服务代理,可以和本地bean一样使用demoService -->  
  <dubbo:reference id="demoService" interface="com.shihuan.zooshare.service.CustomerService" />  
</beans>

logging.properties文件代码如下:
handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ${catalina.base}/logs
org.apache.juli.FileHandler.prefix = error-debug.

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter =java.util.logging.SimpleFormatter

web.xml文件代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<display-name>dubboweb</display-name>
  <context-param>
    <param-name>dubbowebRootKey</param-name>
    <param-value>dubboweb.root</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:jdbc-context.xml,classpath:applicationConsumer.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
	
	<servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <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>
	
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


index.jsp文件代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>index.jsp starting page</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  
  <body>
    <form action="<%=path%>/duboo1.do" method="post">
    	<input type="submit" value="submit" />
    </form>
  </body>
</html>

DubboWebInterceptor.java文件代码如下:
package com.shihuan.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class DubboWebInterceptor extends HandlerInterceptorAdapter {

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
	
	public void postHandler(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String url = request.getRequestURI();
		System.out.println("ConsumerInterceptor.preHandle()" + url);
		
		return super.preHandle(request, response, handler);
	}
	
}

DubboWebController.java文件代码如下:
package com.shihuan.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shihuan.zooshare.service.CustomerService;

@Controller
@RequestMapping(value="/")
public class DubboWebController {

	@Autowired
	public CustomerService demoService;
	
	@RequestMapping(value="duboo1")
	public String duboo1(){
		System.out.println("come into WebController ......");
		String zoosharestr = demoService.getName();
		System.out.println(zoosharestr);
		return "index";
	}
	
	/*
	@RequestMapping(value="duboo1")
	public String duboo1(){
		System.out.println("jinru......");
		return "index";
	}
	*/
	
}

到此为止服务消费者代码编写完毕。
把dubboweb工程部署到tomcat6的webapps目录下即可。

】:各个模块的启动顺序不能错。

第一步:启动zookeeper服务

第二步:启动zooshare.jar服务,控制台应该输出"Press any key to exit."

第三步:启动tomcat6

第四步:访问http://127.0.0.1:8080/governance/applications/

第五步:访问http://127.0.0.1:8080/dubooweb/

第六步:查看tomcat6控制台和zooshare.jar服务控制台是否有正确输出,tomcat6控制台应该输出"come into WebController ......"和"print result !!!",zooshare.jar服务控制台应该输出"shihuan print !!!"


都启动好了后,操作截图如下:














笔者的源代码在[email protected]邮箱网盘的原创作品里。

猜你喜欢

转载自shihuan830619.iteye.com/blog/2245227