dubbo-go go-client/java-client调用

2020年04月07日【回京第二天】16:43:00
补记dubbo-go client调用

dubbo-server端代码增加
user.go

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"context"
	"fmt"
	"time"
)

import (
	hessian "github.com/apache/dubbo-go-hessian2"
	"github.com/apache/dubbo-go/config"
)

func init() {
	config.SetProviderService(new(UserProvider))
	// ------for hessian2------
	hessian.RegisterPOJO(&User{})
}

type User struct {
	Id   string
	Name string
	Age  int32
	Time time.Time
}

type UserProvider struct {
}

// 定义不同的功能,供调用者调用 下面定义了二个功能 GetUser & SearchUser
func (u *UserProvider) GetUser(ctx context.Context, req []interface{}) (*User, error) {
	println("req:%#v", req)
	rsp := User{"A001", "Alex Stocks - Provider return result. 提供者返回的结果。", 18, time.Now()}
	println("rsp:%#v", rsp)
	return &rsp, nil
}

func (u *UserProvider) SearchUser(ctx context.Context, req []interface{}) (*User, error) {
	println("req:%#v", req)
	rsp := User{"A002", "SearchUser 新建立DubboGo提供者返回给Consumer的结果。", 28, time.Now()}
	println("rsp:%#v", rsp)
	return &rsp, nil
}

func (u *UserProvider) Reference() string {
	return "UserProvider"
}

func (u User) JavaClassName() string {
	return "com.ikurento.user.User"
}

func println(format string, args ...interface{}) {
	fmt.Printf("\033[32;40m"+format+"\033[0m\n", args...)
}

其中SearchUser是新增加部分

编译执行
在这里插入图片描述
go-client 修改
在这里插入图片描述
client.go

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"
)

import (
	hessian "github.com/apache/dubbo-go-hessian2"
	"github.com/apache/dubbo-go/common/logger"
	_ "github.com/apache/dubbo-go/common/proxy/proxy_factory"
	"github.com/apache/dubbo-go/config"
	_ "github.com/apache/dubbo-go/protocol/dubbo"
	_ "github.com/apache/dubbo-go/registry/protocol"

	_ "github.com/apache/dubbo-go/filter/filter_impl"

	_ "github.com/apache/dubbo-go/cluster/cluster_impl"
	_ "github.com/apache/dubbo-go/cluster/loadbalance"
	_ "github.com/apache/dubbo-go/registry/zookeeper"
)

var (
	survivalTimeout int = 10e9
)

func println(format string, args ...interface{}) {
	fmt.Printf("\033[32;40m"+format+"\033[0m\n", args...)
}

// they are necessary:
// 		export CONF_CONSUMER_FILE_PATH="xxx"
// 		export APP_LOG_CONF_FILE="xxx"
func main() {
	hessian.RegisterPOJO(&User{})
	config.Load()
	time.Sleep(3e9)

	println("\n\n\nstart to test dubbo")
	user := &User{}
	err := userProvider.SearchUser(context.TODO(), []interface{}{"A001"}, user)
	if err != nil {
		panic(err)
	}
	println("response result: %v\n", user)
	initSignal()
}

func initSignal() {
	signals := make(chan os.Signal, 1)
	// It is not possible to block SIGKILL or syscall.SIGSTOP
	signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGHUP,
		syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	for {
		sig := <-signals
		logger.Infof("get signal %s", sig.String())
		switch sig {
		case syscall.SIGHUP:
			// reload()
		default:
			time.AfterFunc(time.Duration(survivalTimeout), func() {
				logger.Warnf("app exit now by force...")
				os.Exit(1)
			})

			// The program exits normally or timeout forcibly exits.
			fmt.Println("app exit now...")
			return
		}
	}
}

编译执行结果
在这里插入图片描述
看一下go-server

在这里插入图片描述
调用成功

下面看一下Java-client
UserProvider.java

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ikurento.user;

public interface UserProvider {
	User GetUser(String userId);

	User SearchUser(String userId);
}

Consumer.java

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ikurento.user;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Consumer {
    // Define a private variable (Required in Spring)
    private UserProvider userProvider;

    // Spring DI (Required in Spring)
    public void setUserProvider(UserProvider u) {
        this.userProvider = u;
    }

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/dubbo.consumer.xml","META-INF/spring/service.xml");
        context.start();
        context.getBean(Consumer.class).start();
    }

    // Start the entry function for consumer (Specified in the configuration file)
    public void start() {
        System.out.println("\n\ntest");
        testGetUser();
    }

    private void testGetUser() {
        try {
            User user1 = userProvider.SearchUser("A003");
            System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] " +
                    " UserInfo, Id:" + user1.getId() + ", name:" + user1.getName()
                    + ", age:" + user1.getAge() + ", time:" + user1.getTime().toString());

        } catch (Exception e) {
            System.out.println("*************exception***********");
            e.printStackTrace();
        }
    }

}

执行结果
在这里插入图片描述
看一下日志文件logs/stdout.log

Last login: Tue Apr  7 16:49:54 on ttys001
lizhongsu@lizhongdeMacBook-Pro ~ % cd Desktop
lizhongsu@lizhongdeMacBook-Pro Desktop % cd GoStudy
lizhongsu@lizhongdeMacBook-Pro GoStudy % ls
dubbo-go-1.3.0			dubbo-go-1.3.0.zip		dubbo-samples-master		dubbo-samples-master.zip
lizhongsu@lizhongdeMacBook-Pro GoStudy % cd dubbo-samples-master
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=128m; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: UseCMSCompactAtFullCollection is deprecated and will likely be removed in a future release.
2020-04-07/16:57:08.570  INFO:  - using logger: com.alibaba.dubbo.common.logger.log4j.Log4jLoggerAdapter
2020-04-07/16:57:38.634  WARN: com.alibaba.dubbo.common.utils.ConfigUtils.loadProperties(ConfigUtils.java:256) -  [DUBBO] only 1 dubbo.properties file is expected, but 2 dubbo.properties files found on class path: [file:/Users/lizhongsu/Desktop/GoStudy/dubbo-samples-master/golang/helloworld/dubbo/java-client/target/user-info-client-0.2.0/conf/dubbo.properties, jar:file:/Users/lizhongsu/Desktop/GoStudy/dubbo-samples-master/golang/helloworld/dubbo/java-client/target/user-info-client-0.2.0/lib/user-info-client-0.2.0.jar!/dubbo.properties], dubbo version: 2.6.5, current host: 192.168.124.11
2020-04-07/16:57:38.652  INFO: com.alibaba.dubbo.container.Main.main(Main.java:61) -  [DUBBO] Use container type([log4j, spring]) to run dubbo serivce., dubbo version: 2.6.5, current host: 192.168.124.11


test
[16:57:41]  UserInfo, Id:A001, name:Alex Stocks - Provider return result. 提供者返回的结果。, age:18, time:Tue Apr 07 16:57:41 CST 2020
[2020-04-07 16:57:41] Dubbo service server started!
stdout.log (END)

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=128m; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: UseCMSCompactAtFullCollection is deprecated and will likely be removed in a future release.
2020-04-07/17:04:34.971  INFO:  - using logger: com.alibaba.dubbo.common.logger.log4j.Log4jLoggerAdapter
2020-04-07/17:04:35.210  WARN: com.alibaba.dubbo.common.utils.ConfigUtils.loadProperties(ConfigUtils.java:256) -  [DUBBO] only 1 dubbo.properties file is expected, but 2 dubbo.properties files found on class path: [file:/Users/lizhongsu/Desktop/GoStudy/dubbo-samples-master/golang/helloworld/dubbo/java-client/target/user-info-client-0.2.0/conf/dubbo.properties, jar:file:/Users/lizhongsu/Desktop/GoStudy/dubbo-samples-master/golang/helloworld/dubbo/java-client/target/user-info-client-0.2.0/lib/user-info-client-0.2.0.jar!/dubbo.properties], dubbo version: 2.6.5, current host: 192.168.124.11
2020-04-07/17:04:35.220  INFO: com.alibaba.dubbo.container.Main.main(Main.java:61) -  [DUBBO] Use container type([log4j, spring]) to run dubbo serivce., dubbo version: 2.6.5, current host: 192.168.124.11


test
[17:04:36]  UserInfo, Id:A002, name:SearchUser 新建立DubboGo提供者返回给Consumer的结果。, age:28, time:Tue Apr 07 17:04:36 CST 2020
[2020-04-07 17:04:36] Dubbo service server started!
logs/stdout.log (END)

Dubbo-go 可以实现go消费者调用,也同时可以实现java消费者调用。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值