dubbox2.8.4例子教程二

简介

  上篇博客写了个dubbox生产者,也用HttpClient代码测试了rest服务,下面记录dubbox消费者工程

 一、工程结构

  

一、Simple.java

package bhz.entity;

import java.io.Serializable;
import java.util.Map;

public class Simple  implements Serializable
{  
     private static final long serialVersionUID = -4914434736682797743L;  
     private String name;  
     private int age;  
     private Map<String,Integer> map;  
     public Simple(){  
  
     }  
     public Simple(String name,int age,Map<String,Integer> map){  
         this.name = name;  
         this.age = age;  
         this.map = map;  
     }  
  
     public String getName() {  
       return name;  
     }  
  
     public void setName(String name) {  
        this.name = name;  
     }  
  
     public int getAge() {  
        return age;  
     }  
  
     public void setAge(int age) {  
        this.age = age;  
     }  
  
     public Map<String, Integer> getMap() {  
        return map;  
     }  
  
     public void setMap(Map<String, Integer> map) {  
        this.map = map;  
     }  
  
  
}  

二、User.java

package bhz.entity;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonProperty;

@XmlRootElement
public class User  //implements Serializable
{

    @NotNull
    private String id;

    @JsonProperty("name")
    @XmlElement(name = "name")
    @NotNull
    @Size(min = 6, max = 50)
    private String name;
    
    public User() {
    }
    
    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;
    }
    
}

三、SimpleService.java

package bhz.service;

import bhz.entity.Simple;

public interface SimpleService {
    
    public String sayHello(String name);
    public Simple getSimple();
}

四、UserService.java

package bhz.service;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;

import bhz.entity.User;
@Path("/userService")
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public interface UserService {
    @GET
    @Path("/testget")
    public void testget();
    @GET
    @Path("/getUser")
    public User getUser();
    @GET
    @Path("/get/{id : \\d+}")
    public User getUser(@PathParam(value = "id") Integer id);
    @GET
    @Path("/get/{id : \\d+}/{name : [a-zA-Z][0-9]}")
    public User getUser(@PathParam(value = "id") Integer id, @PathParam(value = "name") String name);
    @POST
    @Path("/testpost")
    public void testpost();
    @POST
    @Path("/postUser")
    public User postUser(User user);
    @POST
    @Path("/post/{id}")
    public User postUser(@PathParam(value = "id") String id);

}

五、FastJsonConvert.java(fastJson序列化和反序列化工具类)

package bhz.utils;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;


public class FastJsonConvert {


    private static final SerializerFeature[] featuresWithNullValue = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse,
            SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty };

    /**
     * JsonString 转换 Object
     * 
     * @param <T>
     * @param data
     * @param clzss
     * @return
     */
    public static <T> T convertJSONToObject(String data, Class<T> clzss) {
        try {
            T t = JSON.parseObject(data, clzss);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }
    /**
     * JsonString 转换 List<Object>
     * 
     * @param <T>
     * @param data
     * @param clzss
     * @return
     */
    public static <T> List<T> convertJSONToArray(String data, Class<T> clzss) {
        try {
            List<T> t = JSON.parseArray(data, clzss);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
            
        }
    }

    /**
     * Object to JsonString
     *
     * @param <T>
     * @param data
     * @param valueType
     * @return
     */
    public static String convertObjectToJSON(Object obj) {
        try {
            String text = JSON.toJSONString(obj);
            return text;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Object to JsonString
     *
     * @param <T>
     * @param data
     * @param valueType
     * @return
     */
    public static String convertObjectToJSONWithNullValue(Object obj) {
        try {
            String text = JSON.toJSONString(obj, featuresWithNullValue);
            return text;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        System.err.println(System.getProperties());
    }
}

六、SerializationOptimizerImpl.java(序列化实现类)

package bhz.utils;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import bhz.entity.Simple;
import bhz.entity.User;

import com.alibaba.dubbo.common.serialize.support.SerializationOptimizer;

public class SerializationOptimizerImpl implements SerializationOptimizer {

    public Collection<Class> getSerializableClasses() {
        List<Class> classes = new LinkedList<Class>();
        //这里可以把所有需要进行序列化的类进行添加
        classes.add(User.class);
        classes.add(Simple.class);
        return classes;
    }
}

七、dubbo-consumer.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"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    
    <!-- 引入properties配置文件 -->
    <util:properties id="zcparams" location="classpath:params.properties"></util:properties>

    <dubbo:application name="consumer" owner="programmer" organization="dubbox"/>
    
    <dubbo:registry address="zookeeper://192.168.0.4:2181?backup=192.168.0.5:2181,192.168.0.6:2181"/>
    
    <!-- kryo实现序列化  -->
    <dubbo:protocol name="dubbo" serialization="kryo" optimizer="bhz.utils.SerializationOptimizerImpl" /> 
    
    <!-- 生成远程服务代理,可以像使用本地bean -->
    <dubbo:reference interface="bhz.service.UserService" id="userService" check="false" />  
    <!-- 生成远程服务代理,可以像使用本地bean -->
    <dubbo:reference interface="bhz.service.SimpleService" id="simpleService" /> 
    
</beans>

八、log4j.properties

log4j.rootLogger=INFO, console, file

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.file.File=D:/002_developer/workspace_001/zcmoni.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.logger.org.springframework=WARN

九、Consumer.java(消费者测试类)

package bhz.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import bhz.entity.Simple;
import bhz.service.SimpleService;
import bhz.service.UserService;

public class Consumer {

    public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "dubbo-consumer.xml" });
        context.start();

        SimpleService ss = (SimpleService) context.getBean("simpleService");
        String hello = ss.sayHello("tom");
        System.out.println(hello);
        Simple simple = ss.getSimple();
        System.out.println(simple.getName());
        System.out.println(simple.getAge());
        System.out.println(simple.getMap().get("zhang1"));
        

        UserService us = (UserService) context.getBean("userService");
        
        System.out.println(us.getUser().getName());
        System.out.println(us.getUser().getId());
    }

}

到这里,dubbox消费端就做好了

10、dubbox-admin查看服务

可以看到有两个服务,一个是普通的dubbox服务(SimpleService)另一个是dubbbox的rest服务(UserService)

11、测试结果

hellotom
zhang3
21
2

张三
1001

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值