接口定义:
1 interface IAuthServer{
2 CallReturn_t userAuth(string user,string passwd,int device_type);
3 CallReturn_t registerUser(UserRegisterInfo_t reginfo); // tested
4 };
定义认证服务器接口,userAuth()返回认证用户的token
接口服务实现:
1 import os,os.path,sys,struct,time,traceback,signal,threading,copy,base64
2 import datetime,base64
3
4 from datetime import datetime
5 from base import *
6 import tcelib as tce
7 from showbox import *
8 import utils.misc
9 import utils.config
10 import utils.cipher
11
12
13 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "database.showbox.showbox.settings")
14
15 from django.db import connection
16 from django.db.models import Sum
17 from django.db import transaction
18 # import sns.core.models as cm
19 import database.showbox.core.models as core
20 import database.showbox.nosql.models as nosql
21
22 class AuthServerImpl(IAuthServer):
23 def __init__(self,app):
24 IAuthServer.__init__(self)
25 self.app = app
26
27 def userAuth(self, user, passwd, device_type, ctx):
28 cr = CallReturn_t()
29 try:
30 r = core.User.objects.get(user=user,passwd=passwd)
31 userinfo = {
32 "id":r.id,
33 "user":user,
34 "name":r.name,
35 "login_time":int(time.time()),
36 "user_type":SnsConsts.Authorized_User
37 }
38 token = utils.cipher.encryptToken(userinfo)
39 cr.value = token
40 except:
41 print traceback.format_exc()
42 cr = CallReturn_Error()
43 return cr
44
45 def registerUser(self, reginfo, ctx):
46 return IAuthServer.registerUser(self, reginfo, ctx)
47
48
49
50 class ServerApp:
51 def __init__(self):
52 pass
53
54 def getConfig(self):
55 #return self.app.getConfig()
56 pass
57
58 _handle = None
59 @classmethod
60 def instance(cls):
61 if cls._handle == None:
62 cls._handle = cls()
63 return cls._handle
64
65 def run(self):
66 tce.RpcCommunicator.instance().init('authserver').initMessageRoute('./services.xml')
67 server = tce.RpcCommunicator.instance().currentServer().findEndPointByName('mq_authserver').impl
68 adapter = tce.RpcAdapterEasyMQ.create('server',server)
69 #没有主动发送消息的情形
70 servant = AuthServerImpl(self)
71 adapter.addServant(servant)
72 tce.RpcCommunicator.instance().waitForShutdown()
73
74 if __name__ == '__main__':
75 ServerApp.instance().run()
服务器很简单,实现接口IAuthService的功能函数,定义一个ServerApp,然后运行
客户调用测试:
1 from datetime import datetime
2 from base import *
3 import tcelib as tce
4 from showbox import *
5 import utils.misc
6 import utils.config
7 import utils.cipher
8
9
10 def userAuthResult(result,prx):
11 print result
12
13 # queue:client 必须在调用服务器的write 队列mq
14 communicator =tce.RpcCommunicator.instance().init()
15 conn = tce.RpcConnectionEasyMQ.create('127.0.0.1',12301,'queue:mq_authserver')
16 local = tce.RpcConnectionEasyMQ.create('127.0.0.1',12301,'queue:mq_test_client',tce.AF_READ)
17 conn.setLoopbackMQ(local)
18
19
20 prx = IAuthServerPrx(conn)
21 prx.userAuth_async('test','111111',1,userAuthResult) #异步调用
22 print prx.userAuth('test','111111',1) #同步调用
21,22行分别测试两种调用模式
client与server通过EasyMQ进行传递
easyMQ是个最简单的消息队列实现