Parcourir la Source

在rest和service体系下增加dubbo调用方式

huangbo 6 ans auparavant
Parent
commit
4f5997c2ab

+ 13 - 0
ipu-rest-demo/pom.xml

@ -73,6 +73,19 @@
73 73
			<groupId>com.ai.ipu</groupId>
74 74
			<artifactId>ipu-server-web</artifactId>
75 75
		</dependency>
76
	
77
		<dependency>
78
			<groupId>com.alibaba</groupId>
79
			<artifactId>dubbo</artifactId>
80
		</dependency>
81
		<dependency>
82
		    <groupId>com.github.sgroschupf</groupId>
83
		    <artifactId>zkclient</artifactId>
84
		</dependency>
85
		<dependency>
86
		    <groupId>com.netflix.curator</groupId>
87
		    <artifactId>curator-framework</artifactId>
88
		</dependency>
76 89
		
77 90
		<!-- msgframe相关依赖 -->
78 91
		<dependency>

+ 10 - 3
ipu-rest-demo/src/main/java/com/ai/ipu/server/demo/IpuRestDemoStart.java

@ -1,6 +1,9 @@
1 1
package com.ai.ipu.server.demo;
2 2

3
import org.springframework.context.support.ClassPathXmlApplicationContext;
4

3 5
import com.ai.ipu.restful.boot.IpuRestApplication;
6
import com.ai.ipu.restful.spring.SpringManager;
4 7

5 8
/**
6 9
 * @author huangbo@asiainfo.com
@ -9,7 +12,11 @@ import com.ai.ipu.restful.boot.IpuRestApplication;
9 12
 * @desc 启动的时候需要指定参数--server.port=8080
10 13
 */
11 14
public class IpuRestDemoStart {
12
	public static void main(String[] args) {
13
		IpuRestApplication.start(args);
14
	}
15
    public final static String DUBBO_CONSUMER_CONFIG = "dubbo-consumer-simple.xml";
16
    
17
    public static void main(String[] args) {
18
        SpringManager.registerSpringContext(
19
                new ClassPathXmlApplicationContext(new String[] { DUBBO_CONSUMER_CONFIG }));
20
        IpuRestApplication.start(args);
21
    }
15 22
}

+ 41 - 0
ipu-rest-demo/src/main/java/com/ai/ipu/server/demo/control/dubbo/DubboControl.java

@ -0,0 +1,41 @@
1
package com.ai.ipu.server.demo.control.dubbo;
2

3
import org.springframework.stereotype.Controller;
4
import org.springframework.web.bind.annotation.RequestMapping;
5
import org.springframework.web.bind.annotation.ResponseBody;
6

7
import com.ai.ipu.basic.reflect.ReflectUtil;
8
import com.ai.ipu.basic.util.IpuUtility;
9
import com.ai.ipu.restful.spring.SpringManager;
10
import com.ai.ipu.service.demo.IBizService;
11
import com.ailk.common.data.IData;
12

13
@Controller
14
@RequestMapping("/dubbo")
15
public class DubboControl {
16

17
    @ResponseBody
18
    @RequestMapping("/biz")
19
    public IData callBizService(IData params) {
20
        IBizService bizService = (IBizService)SpringManager.takeSpringContext().getBean("bizService"); // 获取远程服务代理
21
        IData result = bizService.queryUserInfo(params); // 执行远程方法
22
        result.put("msg", "测试biz类型服务调用");
23
        return params;
24
    }
25
    
26
    @ResponseBody
27
    @RequestMapping("/common")
28
    public IData callCommonService(IData params) {
29
        String serviceName = params.getString("service_name");
30
        String methodName = params.getString("method_name");
31
        Object service = SpringManager.takeSpringContext().getBean(serviceName); 
32
        try {
33
            ReflectUtil.invokeMethod(service, methodName, new Object[]{params});
34
        }catch (Exception e) {
35
            // TODO Auto-generated catch block
36
            IpuUtility.error(serviceName + "服务的" + methodName + "方法调用异常:" + e.getMessage());
37
        }
38
        params.put("msg", "测试common类型服务调用");
39
        return params;
40
    }
41
}

+ 0 - 199
ipu-rest-demo/src/main/java/com/ai/ipu/server/demo/control/ipu/IpuController.java

@ -1,199 +0,0 @@
1
package com.ai.ipu.server.demo.control.ipu;
2

3
import java.net.URLDecoder;
4

5
import javax.servlet.http.Cookie;
6
import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpServletResponse;
8

9
import org.apache.log4j.Logger;
10
import org.springframework.stereotype.Controller;
11
import org.springframework.web.bind.annotation.RequestMapping;
12

13
import com.ai.ipu.basic.string.EscapeUnescape;
14
import com.ai.ipu.basic.thread.ThreadLocalManager;
15
import com.ai.ipu.server.config.DataConfig;
16
import com.ai.ipu.server.config.MobileConfig;
17
import com.ai.ipu.server.frame.context.impl.AbstractContextManager;
18
import com.ai.ipu.server.frame.context.impl.DefaultContextManager;
19
import com.ai.ipu.server.frame.handle.IExceptionHandler;
20
import com.ai.ipu.server.frame.session.impl.AbstractSessionManager;
21
import com.ai.ipu.server.frame.session.impl.DefaultSessionManager;
22
import com.ai.ipu.server.servlet.ServletManager;
23
import com.ai.ipu.server.util.MobileConstant;
24
import com.ai.ipu.server.util.MobileUtility;
25
import com.ailk.common.data.IData;
26
import com.ailk.common.data.impl.DataMap;
27

28
/**
29
 * @author huangbo@asiainfo.com
30
 * @team IPU
31
 * @date 2018年4月28日下午5:23:53
32
 * @desc 基于IPU服务端的spring mvc封装。
33
 */
34
@Controller
35
/*增加了mobile路径后,所有的静态资源加载都会执行BasicInterceptor拦截器*/
36
//@RequestMapping("/mobile")
37
public class IpuController {
38
    transient static protected Logger log = Logger.getLogger(IpuController.class);
39
    {
40
        try {
41
            /*初始上下文管理类*/
42
            String ctxClassName = MobileConfig.getValue(MobileConstant.MobileConfig.CONTEXT_MANAGER,
43
                    DefaultContextManager.class.getName());
44
            String sesClassName = MobileConfig.getValue(MobileConstant.MobileConfig.SESSION_MANAGER,
45
                    DefaultSessionManager.class.getName());
46
            if (ctxClassName==null||"".equals(ctxClassName)){
47
                MobileUtility.error("需要指定ContextManager类");
48
            }
49
            if (sesClassName==null||"".equals(sesClassName)){
50
                MobileUtility.error("需要指定SessionManager类");
51
            }
52
            AbstractContextManager.initManageClass(ctxClassName);
53
            AbstractSessionManager.initManageClass(sesClassName);
54
        } catch (Exception e) {
55
            log.error(e.getMessage(), e);
56
        }
57
    }
58
    
59
    
60
    @RequestMapping("/ui")
61
    public void ui(HttpServletRequest request, HttpServletResponse response) {
62
        ServletManager.setRequest(request);
63
        ServletManager.setResponse(response);
64
        
65
        String pageAction = request.getParameter(MobileConstant.Server.ACTION);
66
        String data = request.getParameter(MobileConstant.Server.DATA);
67
        String key = request.getParameter(MobileConstant.Server.KEY);
68
        String is_context = request.getParameter(MobileConstant.Server.IS_CONTEXT);
69
        String isEncode = request.getParameter(MobileConstant.Server.IS_ENCODE);
70
        
71
        long startTime = System.currentTimeMillis();
72
        try {
73
            ServletManager.setPageAction(pageAction); //装载全局pageAction
74
            /*如果是编码的数据或上下文,就进行解码*/
75
            if (data != null && !"{}".equals(data) && "true".equals(isEncode)) {
76
                data = URLDecoder.decode(data, MobileConfig.getValue(MobileConstant.MobileConfig.ENCODE, MobileConstant.UTF_8));
77
            }
78

79
            boolean isContext = false;
80
            if ("true".equals(is_context)) {
81
                isContext = true;
82
            }
83
            
84
            //如果是加密的数据就解密
85
            if(key!=null){
86
                data = ServletManager.getSecurityHandle().requestDecrypt(key, data);
87
            }
88
            //欢迎页初始化
89
            if(pageAction==null){
90
                pageAction = MobileConfig.getValue(MobileConstant.MobileConfig.INDEX_PAGE);
91
            }
92
            
93
            if (log.isDebugEnabled()) {
94
                log.debug(">>> 进入MobileUiServlet post");
95
                log.debug(">>> pageAction: " + pageAction);
96
                log.debug(">>> data: " + data);
97
                log.debug(">>> isContext: " + isContext);
98
            }
99
            IData pageData = null;
100
            if(data==null){
101
                pageData = new DataMap();
102
            }else{
103
                pageData = new DataMap(data);
104
            }
105
            //读cookie,如果传入的参数中包含有某个键,cookie里面对应的同名键值将被忽略
106
            Cookie[] cookies = request.getCookies();     
107
            if(cookies!=null) {   
108
                for (Cookie cookie : cookies) {
109
                    String cookieName = cookie.getName();
110
                    if(!pageData.containsKey(cookieName)){
111
                        String cookieValue = EscapeUnescape.unescape(cookie.getValue());
112
                        pageData.put(cookieName, cookieValue);
113
                    }
114
                } 
115
             }
116
            ServletManager.render(pageAction, pageData, isContext);
117
            
118
        } catch (Exception e) {
119
            log.error("[[[[["+pageAction+"]]]]]] pageAction error", e);
120
            
121
            try {
122
                //语句简单明了,便于调试和排错
123
                IExceptionHandler eHandler = ServletManager.getExceptionHandler();
124
                eHandler.pageError(e, pageAction, data);
125
            } catch (Exception ex) {
126
                log.error(ex.getMessage(),ex);
127
            }
128
        } finally {
129
            ThreadLocalManager.removes();//请求结束时候清除ThreadLocal
130
        }
131
        
132
        if (log.isDebugEnabled()){
133
            double time = ((double) (System.currentTimeMillis() - startTime) / (double) 1000);
134
            log.debug("mobile servlet invoke finish, use time: " + time + "s");
135
        }
136
    }
137
    
138
    @RequestMapping("/data")
139
    public void data(HttpServletRequest request, HttpServletResponse response) throws Exception {
140
        ServletManager.setRequest(request);
141
        ServletManager.setResponse(response);
142
        String dataAction = request.getParameter(MobileConstant.Server.ACTION);
143
        String data = request.getParameter(MobileConstant.Server.DATA);
144
        String key = request.getParameter(MobileConstant.Server.KEY);
145

146
        long startTime = System.currentTimeMillis();
147
        
148
        Object result = null;
149
        try {
150
            ServletManager.setDataAction(dataAction); //装载全局dataAction,需要多次装载,适应多次调用。
151
            // 如果是加密的数据就解密
152
            if ("true".equals(MobileConfig.getValue(MobileConstant.MobileConfig.PRODUCT_MODE)) // 配置productMode=true防止拼串访问
153
                    || (key != null && DataConfig.isEncrypt(dataAction))) {
154
                data = ServletManager.getSecurityHandle().requestDecrypt(key, data);
155
            }
156
            
157
            if (log.isDebugEnabled()) {
158
                log.debug(">>> 进入MobileDataServlet post");
159
                log.debug(">>> dataAction: " + dataAction);
160
                log.debug(">>> data: " + data);
161
            }
162
            
163
            IData param = data==null?new DataMap():new DataMap(data);
164
            result = ServletManager.getBizData(dataAction, param);
165
        } catch (Exception e) {
166
            log.error("[[[[["+dataAction+"]]]]]] dataAction error", e);
167

168
            try {
169
                result = ServletManager.getExceptionHandler().dataError(e, dataAction, data);
170
            } catch (Exception ex) {
171
                result = ex.getMessage();
172
                log.error(ex.getMessage(), ex);
173
            }
174
        }finally{
175
            try {
176
                ServletManager.doResponse(result);
177
            } catch (Exception e) {
178
                log.error(e.getMessage(), e);
179
                String outError = "返回信息加密异常:"+e.getMessage();
180
                response.setHeader("content-type", "text/html; charset=" + ServletManager.encode);
181
                response.setHeader("Content-Length", "" + outError.getBytes(ServletManager.encode).length);
182
                // update by huangbo jcl的BUG已经修复,不用再处理
183
                //outError = outError.replaceAll("\\\\r|\\\\t|\\\\n", "");// 过滤换行制表符
184
                if(log.isDebugEnabled()){
185
                    log.debug(">>> doResponse outstr: " + outError);
186
                }
187
                response.getWriter().print(outError);
188
                response.getWriter().flush();
189
            }finally{
190
                ThreadLocalManager.removes();//请求结束时候清除ThreadLocal
191
            }
192
        }
193
        
194
        if (log.isDebugEnabled()){
195
            double time = ((double) (System.currentTimeMillis() - startTime) / (double) 1000);
196
            log.debug("mobiledata servlet invoke finish, use time: " + time + "s");
197
        }
198
    }
199
}

+ 26 - 0
ipu-rest-demo/src/main/java/com/ai/ipu/service/demo/IBizService.java

@ -0,0 +1,26 @@
1
package com.ai.ipu.service.demo;
2

3
import com.ailk.common.data.IData;
4

5
/**
6
 * @author huangbo@asiainfo.com
7
 * @team IPU
8
 * @date 2018年10月23日下午7:25:11
9
 * @desc 业务服务调用案例
10
 */
11
public interface IBizService {
12

13
    /**
14
     * @author huangbo@asiainfo.com
15
     * @title: queryUserInfo
16
     * @desc: 用户信息查询
17
     */
18
    public IData queryUserInfo(IData param);
19
    
20
    /**
21
     * @author huangbo@asiainfo.com
22
     * @title: triggerException
23
     * @desc: 触发业务异常
24
     */
25
    public IData triggerException(IData param);
26
}

+ 19 - 0
ipu-rest-demo/src/main/resources/dev/dubbo-consumer-simple.xml

@ -0,0 +1,19 @@
1
<?xml version="1.0" encoding="UTF-8"?>
2
<beans xmlns="http://www.springframework.org/schema/beans"
3
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
4
	xsi:schemaLocation="http://www.springframework.org/schema/beans
5
	http://www.springframework.org/schema/beans/spring-beans.xsd
6
	http://code.alibabatech.com/schema/dubbo 
7
	http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
8
	<!-- 全局配置 start=========================== -->
9
	<dubbo:application name="ipu-rest-demo" />
10
	<!-- 关闭重试,延长超时 -->
11
	<dubbo:consumer retries="0" timeout="2000"/>	<!-- client="netty4" -->
12
	<dubbo:registry address="127.0.0.1:20880" /> <!-- 127.0.0.1 -->
13
	<!-- 全局配置 end=========================== -->
14

15
	<!-- 服务注册配置 start=========================== -->
16
	<dubbo:reference id="bizService"
17
		interface="com.ai.ipu.service.demo.IBizService" />
18
	<!-- 服务注册配置 end =========================== -->
19
</beans>

+ 10 - 86
ipu-service-demo/pom.xml

@ -2,9 +2,13 @@
2 2
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3 3
	<modelVersion>4.0.0</modelVersion>
4 4
5
	<groupId>com.ai.ipu.server</groupId>
5
	<parent>
6
		<groupId>com.ai.ipu.server</groupId>
7
		<artifactId>ipu-service-libs</artifactId>
8
		<version>3.0-SNAPSHOT</version>
9
	</parent>
10
6 11
	<artifactId>ipu-service-demo</artifactId>
7
	<version>3.0-SNAPSHOT</version>
8 12
	<packaging>jar</packaging>
9 13
10 14
	<name>ipu-service-demo</name>
@ -24,32 +28,29 @@
24 28
			</snapshots>
25 29
		</repository>
26 30
	</repositories>
31
	
27 32
	<properties>
28 33
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
29 34
		<ipu>3.0-SNAPSHOT</ipu>
30
		<msgframe>2.0.0</msgframe>
35
		<!-- <msgframe>2.0.0</msgframe> -->
31 36
	</properties>
32 37
33 38
	<dependencies>
34 39
		<dependency>
35 40
			<groupId>junit</groupId>
36 41
			<artifactId>junit</artifactId>
37
			<version>3.8.1</version>
38 42
			<scope>test</scope>
39 43
		</dependency>
40 44
		<dependency>
41 45
			<groupId>com.ai.ipu.server</groupId>
42 46
			<artifactId>ipu-service</artifactId>
43
			<version>${ipu}</version>
44 47
		</dependency>
45 48
		<dependency>
46
			<!-- 不依赖其他jar -->
47 49
			<groupId>com.ai.wade</groupId>
48 50
			<artifactId>wade-mobile-data</artifactId>
49
			<version>1.0</version>
50 51
		</dependency>
51 52
		<!-- msgframe相关依赖 -->
52
		<dependency>
53
		<!-- <dependency>
53 54
		  <groupId>com.ai.aif.msgframe</groupId>
54 55
		  <artifactId>msgframe-common</artifactId>
55 56
		  <version>${msgframe}</version>
@ -90,11 +91,6 @@
90 91
		  <version>1.3</version>
91 92
		</dependency>
92 93
		<dependency>
93
  			<groupId>javax.jms</groupId>
94
  			<artifactId>jms</artifactId>
95
  			<version>1.1</version>
96
		</dependency>
97
		<dependency>
98 94
		  <groupId>org.apache.kafka</groupId>
99 95
		  <artifactId>kafka-clients</artifactId>
100 96
		  <version>0.10.2.0</version>
@ -108,78 +104,6 @@
108 104
   			<groupId>com.alibaba.rocketmq</groupId>
109 105
    		<artifactId>rocketmq-client</artifactId>
110 106
    		<version>3.5.9</version>
111
		</dependency>
107
		</dependency> -->
112 108
	</dependencies>
113
	
114
	<!-- 对应开发、测试、生产三种环境 -->
115
	<profiles>
116
		<!-- 开发环境 -->
117
		<profile>
118
			<id>dev</id>
119
			<properties>
120
				<env>dev</env>
121
			</properties>
122
			<activation>
123
				<activeByDefault>true</activeByDefault>
124
			</activation>
125
		</profile>
126
		<!-- 测试环境 -->
127
		<profile>
128
			<id>test</id>
129
			<properties>
130
				<env>test</env>
131
			</properties>
132
		</profile>
133
		<!-- 生产环境 -->
134
		<profile>
135
			<id>pro</id>
136
			<properties>
137
				<env>pro</env>
138
			</properties>
139
		</profile>
140
	</profiles>
141
	<build>
142
		<plugins>
143
			<plugin>
144
				<groupId>org.apache.maven.plugins</groupId>
145
				<artifactId>maven-surefire-plugin</artifactId>
146
				<configuration>
147
					<!-- 跳过单元测试 -->
148
					<skip>true</skip>
149
				</configuration>
150
			</plugin>
151
			
152
			<plugin>
153
				<groupId>org.apache.maven.plugins</groupId>
154
				<artifactId>maven-compiler-plugin</artifactId>
155
				<configuration>
156
					<source>1.8</source>
157
					<target>1.8</target>
158
					<encoding>UTF-8</encoding>
159
					<!-- 这里添加本地jar -->
160
					<compilerArguments>
161
 					<!-- <bootclasspath>${JAVA_HOME}/jre/lib/rt.jar</bootclasspath> -->
162
 					<bootclasspath>/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar</bootclasspath>
163
 					<extdirs>${project.basedir}/libs</extdirs>
164
					</compilerArguments>
165
				</configuration>
166
			</plugin>
167
		</plugins>
168
		<resources>
169
            <resource>
170
                <directory>src/main/resources</directory>
171
                <!-- 资源根目录排除各环境的配置,防止在生成目录中多余其它目录 -->
172
                <excludes>
173
                    <exclude>dev/*</exclude>
174
                    <exclude>test/*</exclude>
175
                    <exclude>pro/*</exclude>
176
                </excludes>
177
            </resource>
178
            <resource>
179
                <directory>src/main/resources/${env}</directory>
180
                <!-- 根据输入参数动态修改相关内容 -->
181
				<filtering>true</filtering>
182
            </resource>
183
        </resources>
184
	</build>
185 109
</project>

+ 2 - 4
ipu-service-demo/src/main/java/com/ai/ipu/service/IpuServiceDemoStart.java

@ -2,8 +2,6 @@ package com.ai.ipu.service;
2 2

3 3
import org.springframework.context.support.ClassPathXmlApplicationContext;
4 4

5
import com.ai.aif.msgframe.consumer.MfServiceStartup;
6

7 5
public class IpuServiceDemoStart {
8 6
    public final static String MODE = "simple";
9 7
    public final static String DUBBO_PROVIDER_CONFIG = "dubbo-provider-" + MODE + ".xml";
@ -16,9 +14,9 @@ public class IpuServiceDemoStart {
16 14
        context.start();
17 15
        /*启动消息中间件的消费者服务*/
18 16
        /*启动所有的订阅*/
19
        MfServiceStartup.main();
17
        //MfServiceStartup.main();
20 18
        /*启动指定的订阅*/
21
//        MfConsumerClient.subscribe("myTestTopic", "*", "com.ai.ipu.service.demo.consumer.ConsumerProcessorImpl");
19
        //MfConsumerClient.subscribe("myTestTopic", "*", "com.ai.ipu.service.demo.consumer.ConsumerProcessorImpl");
22 20
        System.in.read(); // press any key to exit
23 21
    }
24 22
}

+ 6 - 6
ipu-service-demo/src/main/java/com/ai/ipu/service/demo/consumer/ConsumerProcessorImpl.java

@ -2,17 +2,17 @@ package com.ai.ipu.service.demo.consumer;
2 2

3 3
import org.springframework.context.support.ClassPathXmlApplicationContext;
4 4

5
import com.ai.aif.msgframe.common.IConsumerProcessor;
6
import com.ai.aif.msgframe.common.exception.ConsumerException;
7
import com.ai.aif.msgframe.common.message.MsgFMessage;
8
import com.ai.aif.msgframe.common.message.MsgFTextMessage;
5
//import com.ai.aif.msgframe.common.IConsumerProcessor;
6
//import com.ai.aif.msgframe.common.exception.ConsumerException;
7
//import com.ai.aif.msgframe.common.message.MsgFMessage;
8
//import com.ai.aif.msgframe.common.message.MsgFTextMessage;
9 9
import com.ai.ipu.service.IpuServiceDemoStart;
10 10
import com.ai.ipu.service.demo.IDbService;
11 11
import com.ailk.common.data.IData;
12 12
import com.ailk.common.data.impl.DataMap;
13 13

14 14

15
public class ConsumerProcessorImpl implements IConsumerProcessor {
15
/*public class ConsumerProcessorImpl implements IConsumerProcessor {
16 16

17 17
    public Object process(MsgFMessage msg) throws ConsumerException{
18 18
        ClassPathXmlApplicationContext context = 
@ -30,4 +30,4 @@ public class ConsumerProcessorImpl implements IConsumerProcessor {
30 30
        return true;
31 31
    }
32 32

33
}
33
}*/