zookeeper+dubbo和spring的整合

来源:互联网 发布:如何安装php开发环境 编辑:程序博客网 时间:2024/05/17 23:03

  搭建zookeeper之后,启动本地zookeeper服务。具体教程可参考:http://blog.csdn.net/hh12211221/article/details/76849717

创建maven项目

http://write.blog.csdn.net/postedit


  • bookserviceImpl:java项目,作为serviceImpl和dao层的提供者;
  • bookstoreapi:java项目,存放公共接口(service是serviceImpl的接口)及实体层,该项目均被其余两个项目依赖;
  • bookStore:web项目,存放controller和页面。

bookstoreapi项目

bookstoreapi项目的目录结构为


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>com.cn.bookstore</groupId><artifactId>bookstoreapi</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><!-- mongodb开始 --><dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.3.0</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-mongodb</artifactId><version>1.7.1.RELEASE</version></dependency><!-- mongodb结束 --></dependencies><build><finalName>bookstoreapi</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>2.1</version><configuration><source>1.7</source><target>1.7</target><encoding>UTF-8</encoding><failOnError>false</failOnError></configuration></plugin></plugins></build></project>

Book.java代码

package com.book.book.model;import java.io.Serializable;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;@Document(collection = "book")public class Book implements Serializable{@Idprivate String id;// 书名private String name;// 作者private String author;// 价格private float price;// 图书封面private String picture;// 图书存储量private Integer stock;// 售出量private int sale;// 图书简介private String message;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}public String getPicture() {return picture;}public void setPicture(String picture) {this.picture = picture;}public Integer getStock() {return stock;}public void setStock(Integer stock) {this.stock = stock;}public int getSale() {return sale;}public void setSale(int sale) {this.sale = sale;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}

BookService.java代码

package com.book.book.service;/* * 图书管理 */public interface BookService {/* * 查询所有图书 */public String FindAll();/* * 根据图书名获取所有图书——模糊查询 *  * @name 图书名 *  * @return */public String getByName(String name);/* * 根据作者获取所有图书——模糊查询 *  * @author 作者 *  * @return */public String getByAuthor(String author);/* * 根据id获取所有图书 *  * @id 图书id *  * @return */public String getById(String id);}

bookserviceImpl项目(服务提供方)

bookserviceImpl项目目录结构为


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>com.cn.bookstore</groupId><artifactId>bookserviceImpl</artifactId><version>0.0.1-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring.version>4.2.5.RELEASE</spring.version><slf4j.version>1.6.6</slf4j.version></properties><dependencies><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.2.2</version></dependency><dependency><groupId>com.cn.bookstore</groupId><artifactId>bookstoreapi</artifactId><version>0.0.1-SNAPSHOT</version></dependency><dependency><groupId>net.paoding</groupId><artifactId>paoding-rose-jade</artifactId><version>2.0.u08</version></dependency><dependency><groupId>net.paoding</groupId><artifactId>paoding-rose-web</artifactId><version>2.0.u08</version><exclusions><exclusion><artifactId>spring-web</artifactId><groupId>org.springframework</groupId></exclusion><exclusion><artifactId>spring-context</artifactId><groupId>org.springframework</groupId></exclusion><exclusion><artifactId>spring-expression</artifactId><groupId>org.springframework</groupId></exclusion></exclusions></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpasyncclient</artifactId><version>4.0-beta3</version><scope>compile</scope></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><dependency><groupId>com.alibaba</groupId><artifactId>dubbo</artifactId><version>2.8.4</version></dependency><!-- zkclient --><dependency><groupId>com.github.sgroschupf</groupId><artifactId>zkclient</artifactId><version>0.1</version></dependency><!-- zookeeper --><dependency><groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId><version>3.3.6</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</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-expression</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jmx</artifactId><version>2.0.8</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version><type>jar</type></dependency><!-- spring end --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.26</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>3.2.1</version></dependency><dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>1.0.0.GA</version></dependency><!-- 如果要使用json序列化 --><dependency><groupId>org.jboss.resteasy</groupId><artifactId>resteasy-jackson-provider</artifactId><version>3.0.7.Final</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>dubbo-rpc-rest</artifactId><version>2.8.4</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>dubbo-rpc-rmi</artifactId><version>2.8.4</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.4</version></dependency><!-- mongodb开始 --><dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.3.0</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-mongodb</artifactId><version>1.7.1.RELEASE</version></dependency><!-- mongodb结束 --></dependencies><build><finalName>bookserviceImpl</finalName><resources><resource><directory>${basedir}/src/main/resources                </directory><includes><include>**/*</include></includes></resource><resource><directory>${basedir}/src/main/java</directory><excludes><exclude>**/*.class</exclude><exclude>**/*.java</exclude></excludes></resource></resources><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>2.1</version><configuration><source>1.7</source><target>1.7</target><encoding>UTF-8</encoding><failOnError>false</failOnError></configuration></plugin></plugins></build></project>

在服务提供方实现接口(对服务消费方隐藏实现)

package com.book.book.service;import java.util.ArrayList;import java.util.List;import javax.ws.rs.Path;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.data.mongodb.core.query.Criteria;import org.springframework.data.mongodb.core.query.Query;import org.springframework.stereotype.Service;import com.book.book.model.Book;import net.sf.json.JSONObject;@Path("/Book")@Servicepublic class BookServiceImpl implements BookService {@Autowired@Qualifier("mongoTemplate")MongoTemplate mongoTemplate;public String FindAll() {JSONObject jsonObject = new JSONObject();try {List<Book> bookList = new ArrayList<Book>();bookList = mongoTemplate.findAll(Book.class);jsonObject.put("result", 1);jsonObject.put("msg", bookList);} catch (Exception e) {jsonObject.put("result", 0);jsonObject.put("msg", "接口异常,请联系管理员!");}return jsonObject.toString();}public String getByName(String name) {JSONObject jsonObject = new JSONObject();try {Criteria criteria = new Criteria();criteria.andOperator(Criteria.where("name").regex(".*?\\" + name + ".*"));List<Book> bookList = new ArrayList<Book>();bookList = mongoTemplate.find(new Query(criteria), Book.class);jsonObject.put("result", 1);jsonObject.put("msg", bookList);} catch (Exception e) {jsonObject.put("result", 0);jsonObject.put("msg", "接口异常,请联系管理员!");}return jsonObject.toString();}public String getByAuthor(String author) {JSONObject jsonObject = new JSONObject();try {Criteria criteria = new Criteria();criteria.andOperator(Criteria.where("author").regex(".*?\\" + author + ".*"));List<Book> bookList = new ArrayList<Book>();bookList = mongoTemplate.find(new Query(criteria), Book.class);jsonObject.put("result", 1);jsonObject.put("msg", bookList);} catch (Exception e) {jsonObject.put("result", 0);jsonObject.put("msg", "接口异常,请联系管理员!");}return jsonObject.toString();}public String getById(String id) {JSONObject jsonObject = new JSONObject();try {Criteria criteria = new Criteria();criteria.andOperator(Criteria.where("id").is(id));List<Book> bookList = new ArrayList<Book>();bookList = mongoTemplate.find(new Query(criteria), Book.class);jsonObject.put("result", 1);jsonObject.put("msg", bookList);} catch (Exception e) {jsonObject.put("result", 0);jsonObject.put("msg", "接口异常,请联系管理员!");}return jsonObject.toString();}}

Spring配置声明暴露服务

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"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://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-2.5.xsd    http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-2.5.xsd        http://code.alibabatech.com/schema/dubbo          http://code.alibabatech.com/schema/dubbo/dubbo.xsd          "><!-- 提供方应用名称信息,这个相当于起一个名字,在使用dubbo管理页面时可以比较清楚地知道是哪个应用暴露出来的 --><dubbo:application name="bookserviceImpl" /><!-- 使用zookeeper注册中心暴露服务地址 --><!-- 1)register是否向此注册中心注册服务,如果设为false,将只订阅,不注册。              2)check注册中心不存在时,是否报错。             3)subscribe是否向此注册中心订阅服务,如果设为false,将只注册,不订阅。      4)timeout注册中心请求超时时间(毫秒)。 5)address可以Zookeeper集群配置,地址可以多个以逗号隔开等。 --><dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"timeout="100000" /><!-- 用dubbo协议在port(端口)暴露服务 --><dubbo:protocol host="192.168.1.230" port="20880" name="dubbo"id="dubbo" /><dubbo:protocol host="192.168.1.230" port="20881" name="rmi"id="rmi" /><dubbo:protocol host="192.168.1.230" port="8081" name="rest"id="rest" /><!-- 具体实现的bean --><bean id="demoService" class="com.book.demo.service.DemoServiceImpl" /><bean id="userService" class="com.book.user.service.UserServiceImpl" /><bean id="bookService" class="com.book.book.service.BookServiceImpl" /><!-- 要暴露的服务接口 --><!--1)interface服务接口的路径                2)ref引用对应的实现类的Bean的ID                3)registry向指定注册中心注册,在多个注册中心时使用,值为<dubbo:registry>的id属性,                  多个注册中心ID用逗号分隔,如果不想将该服务注册到任何registry,可将值设为N/A        4)register 默认true ,该协议的服务是否注册到注册中心 --><dubbo:service interface="com.book.demo.service.DemoService"ref="demoService" timeout="10000" /><dubbo:service interface="com.book.user.service.UserService"ref="userService" timeout="10000" /><dubbo:service interface="com.book.book.service.BookService"ref="bookService" timeout="10000" /><dubbo:monitor protocol="registry" /></beans>

启动服务

   加载Spring的相关配置,启动服务(或者将项目建为web项目,然后在web.xml中配置好sprin的启动,然后扔到tomcat中即可提供服务)

package com.book.main;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"application-provider.xml", "applicationContext-restTemplate.xml", "applicationContext.xml" });System.out.println("服务启动");context.start();}}

bookStore项目(服务消费方)

bookStore项目的目录结构为

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>com.cn.bookstore</groupId><artifactId>bookStore</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring.version>4.2.5.RELEASE</spring.version></properties><dependencies><dependency><groupId>com.cn.bookstore</groupId><artifactId>bookstoreapi</artifactId><version>0.0.1-SNAPSHOT</version></dependency><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.2.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.7</version></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.1</version></dependency><dependency><groupId>javax.ws.rs</groupId><artifactId>javax.ws.rs-api</artifactId><version>2.0.1</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-expression</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-web</artifactId><version>${spring.version}</version><exclusions><exclusion><artifactId>spring-context</artifactId><groupId>org.springframework</groupId></exclusion></exclusions></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session</artifactId><version>1.2.0.RC1</version><type>pom</type></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>net.paoding</groupId><artifactId>paoding-rose</artifactId><version>2.0.u08</version><exclusions><exclusion><artifactId>spring-web</artifactId><groupId>org.springframework</groupId></exclusion><exclusion><artifactId>spring-context</artifactId><groupId>org.springframework</groupId></exclusion></exclusions></dependency><dependency><groupId>net.paoding</groupId><artifactId>paoding-rose-web</artifactId><version>2.0.u08</version><exclusions><exclusion><artifactId>spring-web</artifactId><groupId>org.springframework</groupId></exclusion><exclusion><artifactId>spring-context</artifactId><groupId>org.springframework</groupId></exclusion><exclusion><artifactId>spring-expression</artifactId><groupId>org.springframework</groupId></exclusion></exclusions></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.26</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.4</version></dependency><!-- mongodb开始 --><dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.3.0</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-mongodb</artifactId><version>1.7.1.RELEASE</version></dependency><!-- mongodb结束 --><!-- dubbo+zookeeper开始 --><dependency><groupId>com.alibaba</groupId><artifactId>dubbo</artifactId><version>2.8.4</version></dependency><!-- zkclient --><dependency><groupId>com.github.sgroschupf</groupId><artifactId>zkclient</artifactId><version>0.1</version></dependency><!-- zookeeper --><dependency><groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId><version>3.3.6</version></dependency><dependency><groupId>org.jboss.resteasy</groupId><artifactId>resteasy-client</artifactId><version>3.0.7.Final</version></dependency><!-- 结束 --></dependencies><build><resources><resource><directory>src/main/resources</directory><includes><include>**/*.*</include></includes></resource></resources><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>2.0.2</version><configuration><webResources><resource><targetPath>WEB-INF</targetPath><filtering>true</filtering><directory>src/main/resources</directory><includes><include>**/*.xml</include><include>**/*.properties</include></includes><targetPath>WEB-INF</targetPath></resource></webResources></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>2.1</version><configuration><source>1.7</source><target>1.7</target><encoding>UTF-8</encoding><compilerArguments><sourcepath>${project.basedir}/src/main/java</sourcepath></compilerArguments><failOnError>false</failOnError></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><configuration><!-- 忽略测试 --><skip>true</skip></configuration></plugin></plugins></build></project>

BookController.java

package com.book.controllers;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.data.mongodb.core.aggregation.Aggregation;import org.springframework.data.mongodb.core.query.Criteria;import org.springframework.data.mongodb.core.query.Query;import org.springframework.stereotype.Controller;import org.springframework.web.client.RestTemplate;import com.book.book.model.Book;import com.book.book.service.BookService;import com.book.demo.service.DemoService;import net.paoding.rose.web.annotation.Param;import net.paoding.rose.web.annotation.Path;import net.paoding.rose.web.annotation.rest.Get;@Controller@Path("/")public class BookController {@AutowiredBookService bookService;@AutowiredMongoTemplate mongoTemplate;@AutowiredRestTemplate restTemplate;@AutowiredDemoService demoService;@Get("findAllBooks")public String FindAll() {String url = "http://yz4.chaoxing.com/common/appindex?companyId=1385";//String result = restTemplate.getForObject(url, String.class);//System.out.println(result);String bookList = bookService.FindAll();return "@" + bookList;}@Get("getByName")public String getByName(@Param("name") String name) {String bookList = bookService.getByName(name);return "@" + bookList;}@Get("getByAuthor")public String getByAuthor(@Param("author") String author) {String bookList = bookService.getByAuthor(author);return "@" + bookList;}@Get("getById")public String getById(String id) {String bookList = bookService.getById(id);return "@" + bookList;}}

Spring配置

   通过spring配置引用远程服务,配置如下。

<?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"xmlns:context="http://www.springframework.org/schema/context"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://code.alibabatech.com/schema/dubbo          http://code.alibabatech.com/schema/dubbo/dubbo.xsd          "><!-- 消费方应用名,用于计算以来关系,不是匹配条件,不需要与提供方一样 --><dubbo:application name="bookStore" /><dubbo:registry protocol="zookeeper" address="127.0.0.1"port="2181" timeout="100000" /><!-- 生成远程服务代理,可以像使用本地bean一样使用demoService --><dubbo:reference id="demoService" interface="com.book.demo.service.DemoService"protocol="dubbo" timeout="100000" url="dubbo://192.168.1.230:20880" /><dubbo:reference id="userService" interface="com.book.user.service.UserService"protocol="dubbo" timeout="100000" url="dubbo://192.168.1.230:20880" /><dubbo:reference id="bookService" interface="com.book.book.service.BookService"protocol="dubbo" timeout="100000" url="dubbo://192.168.1.230:20880" /></beans>

启动服务,运行项目即可!至此zookeeper、dubbo和springmvc的整合结束。在项目中使用到rose框架、restTemplate、mysql、mongodb数据库的配置。详细代码可参考:http://download.csdn.net/download/hh12211221/9957332

原创粉丝点击