springmvc+dubbo+zookeeper

9 篇文章 0 订阅
3 篇文章 0 订阅
笔者这里使用的是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目录下,如下图
[img]http://dl2.iteye.com/upload/attachment/0111/8812/3596a217-ba60-322e-965d-308f473899c2.jpg[/img]
修改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/
[color=blue]登录的用户名和密码都是root,不是root/guest[/color]
[img]http://dl2.iteye.com/upload/attachment/0111/8832/52a83988-852b-3a05-aee4-db12f345a054.jpg[/img]
到此为止dubbo-admin-2.5.4.war管理控制台安装完毕。


下面编写服务提供者代码:
[img]http://dl2.iteye.com/upload/attachment/0111/8818/c018a8ad-9c20-36e0-8db9-477cd76f6a0e.jpg[/img]
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>


[color=red]zooshare.jar[/color]服务的结构如下图所示:
[img]http://dl2.iteye.com/upload/attachment/0111/8822/753a6160-4a5c-3459-9981-bc16747ed31d.jpg[/img]

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文件截图([color=red]这里要把zooshare.jar加进来[/color])
[img]http://dl2.iteye.com/upload/attachment/0111/8824/d32d043d-e53c-3718-ba3d-dbb0514898f6.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8826/c1ad9fff-bc4d-3bd5-b85a-aec65ccd342e.jpg[/img]
dubooweb工程总体结构图
[img]http://dl2.iteye.com/upload/attachment/0111/8828/eea8434c-55e4-307f-b6e2-5e79efecb780.jpg[/img]
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目录下即可。

【[color=orange]注[/color]】:各个模块的启动顺序不能错。

第一步:启动zookeeper服务
[img]http://dl2.iteye.com/upload/attachment/0111/8854/3bcfa21b-1965-3a36-94b6-fbca47dcf1e7.jpg[/img]
第二步:启动zooshare.jar服务,控制台应该输出"Press any key to exit."
[img]http://dl2.iteye.com/upload/attachment/0111/8856/4b154e04-540c-3fff-bb1c-8511d528e39c.jpg[/img]
第三步:启动tomcat6
[img]http://dl2.iteye.com/upload/attachment/0111/8858/e4af1f60-a858-345c-8e07-e4540ff96a55.jpg[/img]
第四步:访问http://127.0.0.1:8080/governance/applications/
[img]http://dl2.iteye.com/upload/attachment/0111/8832/52a83988-852b-3a05-aee4-db12f345a054.jpg[/img]
第五步:访问http://127.0.0.1:8080/dubooweb/
[img]http://dl2.iteye.com/upload/attachment/0111/8850/25b52071-a02c-3039-bc57-afc9b5166d20.jpg[/img]
第六步:查看tomcat6控制台和zooshare.jar服务控制台是否有正确输出,tomcat6控制台应该输出"come into WebController ......"和"print result !!!",zooshare.jar服务控制台应该输出"shihuan print !!!"


都启动好了后,操作截图如下:
[img]http://dl2.iteye.com/upload/attachment/0111/8834/2533cf9a-4b1c-3785-906c-cd7c72ac2a41.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8836/18d732a1-c760-39da-875c-a73e053da87b.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8838/8645cb53-cb51-36ac-b15e-c35abe9006c9.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8840/922188e2-a3c1-3392-9311-0a27b337cd26.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8842/3b38c545-4647-395a-b5ba-153a40c32f1c.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8844/8d448081-8980-3d9e-8eb7-e71d5b3d6155.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8846/37687241-3363-3b27-8a6b-ce6b0a87851e.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8848/84669432-af13-3ce9-aa1b-4a58bfa29744.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8852/df6dcbe5-a317-364e-b1fb-62b4b0ad3306.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8860/f2fbb85a-2109-386f-8fd9-c8904990ec56.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8862/ddff078d-c357-3a1e-b6a8-3df21f6f2eae.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0111/8864/3b2c0174-84f9-38fc-bcb5-8867329982e3.jpg[/img]


笔者的源代码在shihuan830619@163.com邮箱网盘的原创作品里。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值