Use the dubbo distributed service framework to publish and consume services, and the dubbo framework to publish and consume

Source: Internet
Author: User

Use the dubbo distributed service framework to publish and consume services, and the dubbo framework to publish and consume
What is DUBBO?

DUBBO is a distributed service framework designed to provide high-performance and transparent RPC remote service calling solutions.

Preparations for zookeeper Installation

ZooKeeper is a distributed, open-source distributed application Coordination Service.

Specific installation steps: For more information, see online resources.

After the installation is complete, configure the zoo. cfg configuration file, which contains a port configuration. I configured port 2181, and the client will use this port to connect to the service.

The ip address of the zookeeper server is 10.0.10.51.

Install dubbo-admin

Dubbo-admin is the dubbo console.

Specific installation steps: For details, refer to the online resources. It is actually a war package and can be deployed to tomcat.

After deployment, modify dubbo. properties configuration file content, set dubbo. registry. the address registration address is configured as the address of the zookeeper service, and the console access password can be configured as follows.

dubbo.registry.address=zookeeper://10.0.10.51:2181?backup=127.0.0.1:2182,127.0.0.1:2183dubbo.admin.root.password=rootdubbo.admin.guest.password=guest

Access http: // 10.0.10.51/dubbo-admin-2.5.3/, the effect is as follows:

Engineering Structure

We will use maven to manage and build the project. The project structure is as follows:

First, create a maven project, including four modules:

    <modules>        <module>dubbo-demo-common</module>        <module>dubbo-demo-api</module>        <module>dubbo-demo-service</module>        <module>dubbo-demo-web</module>    </modules>

Dubbo-demo-service is our service module. Other common modules mainly include model, log, and base class. api modules include service interfaces; service implementation is placed in the service module. The web module is our service consumption module. It is a spring mvc project that calls our published services;

Service provision

In the dubbo-demo-service module, we will use the spring + mybatis framework;

I will not talk about the configurations of spring and mybatis.

Here, we mainly focus on service services. We usually write a service and use the spring annotation @ Autowired in the service to inject dao bean, then, use the dubbo annotation @ Service to mark the service as a dubbo Service. The following is an example of UserServiceImpl:

package org.dubbo.demo.service.user.impl;import java.util.List;import java.util.Map;import org.dubbo.demo.api.service.IUserService;import org.dubbo.demo.common.model.User;import org.dubbo.demo.dao.IUserDao;import org.springframework.beans.factory.annotation.Autowired;import com.alibaba.dubbo.config.annotation.Service;@Service(interfaceClass = IUserService.class)public class UserServiceImpl implements IUserService{    @Autowired    private IUserDao userDao;    @Override    public List<User> queryAll(Map<String, Object> param) throws Exception    {        return userDao.queryAll(param);    }    @Override    public void saveUser(Map<String, Object> param) throws Exception    {        userDao.saveUser(param);    }    @Override    public void deleteUser(Map<String, Object> param) throws Exception    {        userDao.deleteUser(param);    }}

In this way, our service has been written. Is it easy to find? configure dubbo as follows:

<? 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 https://git.oschina.net/pi.chen/wendang/raw/master/dubbo.xsd"> <! -- Application name, used to calculate dependencies. It is not a matching condition and must not be the same as the provider --> <dubbo: application name = "dubbo-demo-service"/> <! -- Use the zookeeper broadcast registry to expose the Discovery Service address --> <dubbo: registry protocol = "zookeeper" address = "10.0.10.51: 2181"/> <! -- Expose services on port 20880 using dubbo protocol --> <dubbo: protocol name = "dubbo" port = "20880"/> <! -- Scan package --> <dubbo: annotation package = "org. dubbo. demo. service"/> </beans>

Finally, write a startup class to start the spring container, as shown in the following example:

package org.dubbo.demo;import org.dubbo.demo.common.log.Logger;import org.springframework.context.support.ClassPathXmlApplicationContext;public class StartDubboService{    private static Logger logger = Logger.getLogger(StartDubboService.class);    public static void main(String[] args)    {        try        {            @SuppressWarnings("resource")            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring.xml");            context.start();            logger.info("context start success.");        }        catch (Exception e)        {            logger.error("context start error.", e);        }        synchronized (StartDubboService.class)        {            while (true)            {                try                {                    StartDubboService.class.wait();                }                catch (InterruptedException e)                {                    logger.error("synchronized error.", e);                }            }        }    }}

Bind the main method to the test stage of maven,

Then we execute the clean test-f service-pom.xml command to start the service (the service-pom.xml is specified here to build only the modules defined in the file );

After the service is published, you can view our service provider on the dubbo console, for example:

Service consumption

After the provider releases the service, the consumer can start to call the service. The consumer will simulate the service using a Java web project using the spring-mvc framework, that is, the dubbo-demo-web module mentioned earlier. This module is very simple. Configure spring-mvc and dubbo, and then use the service "com. alibaba. dubbo. config. annotation. reference "annotation injection, the following is a UserController:

package org.dubbo.demo.controller.user;import java.util.HashMap;import java.util.List;import java.util.Map;import org.dubbo.demo.api.service.IUserService;import org.dubbo.demo.common.base.BaseController;import org.dubbo.demo.common.model.User;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.alibaba.dubbo.config.annotation.Reference;import com.google.gson.Gson;@Controller@RequestMapping(value = "/user")public class UserController extends BaseController{    @Reference    private IUserService userService;    @RequestMapping(value = "/getUserList", produces = "application/json; charset=utf-8")    @ResponseBody    public String getUserList(int pageNo, int pageSize)    {        Gson gson = new Gson();        Map<String, Object> map = new HashMap<String, Object>();        try        {            Map<String, Object> param = new HashMap<String, Object>();            param.put("pageNo", pageNo);            param.put("pageSize", pageSize);            List<User> userList = userService.queryAll(param);            map.put("userList", userList);            return gson.toJson(map);        }        catch (Exception e)        {            logger.error(e.toString(), e);        }        return gson.toJson("faild");    }    @RequestMapping(value = "/deleteUser", produces = "application/json; charset=utf-8")    @ResponseBody    public String deleteUser(int userId)    {        Gson gson = new Gson();        try        {            Map<String, Object> param = new HashMap<String, Object>();            param.put("userId", userId);            userService.deleteUser(param);            return gson.toJson("success");        }        catch (Exception e)        {            logger.error(e.toString(), e);        }        return gson.toJson("faild");    }    @RequestMapping(value = "/saveUserTest", produces = "application/json; charset=utf-8")    @ResponseBody    public String saveUserTest(String userName, String address)    {        Gson gson = new Gson();        try        {            Map<String, Object> param = new HashMap<String, Object>();            param.put("name", userName);            param.put("address", address);            userService.saveUser(param);        }        catch (Exception e)        {            logger.error(e.toString(), e);            return gson.toJson("fail");        }        return gson.toJson("success");    }}

After the project is configured, start our web project and enter the "clean tomcat: run-f web-pom.xml" command,

Then, start to call controller and enter http: // localhost: 8080/dubbo-demo-web/user/getUserList. do? In the browser? PageNo = 0 & pageSize = 5

The service is successfully called and the correct result is obtained:

Similarly, you can see the consumer application on the dubbo Management page:

Engineering source code

Https://github.com/peterchenhdu/Demos/tree/master/dubbo-demo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.