Parcourir la Source

简化ipu-rest-scaffold工程,删除Nacos范例。

huangbo 4 ans auparavant
Parent
commit
81c3d7dcce

+ 11 - 1
ipu-rest-scaffold/readme.md

@ -153,4 +153,14 @@ java -Dipu.lic.path=ipu.lic -jar ipu-rest-scaffold.jar --server.port=8080
153 153
首页界面:菜单层级设置;
154 154

155 155

156
yml和properties格式转换:http://toyaml.com/
156
yml和properties格式转换:http://toyaml.com/
157

158
###编译报错
159
repo.maven.apache.org/151.101.196.215  failed: Connection timed out: connect
160
解决方法:增加阿里的镜像。
161
<mirror>
162
  <id>alimaven</id>
163
  <name>aliyun maven</name>
164
  <mirrorOf>central</mirrorOf>
165
  <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
166
</mirror>

+ 0 - 34
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/config/NacosConfig.java

@ -1,34 +0,0 @@
1
package com.ai.ipu.server.config;
2

3

4
import org.springframework.context.annotation.Bean;
5
import org.springframework.context.annotation.Configuration;
6

7
import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
8
import com.alibaba.nacos.api.config.annotation.NacosValue;
9

10

11
@Configuration
12
public class NacosConfig {
13
	//在Configuration中动态更新将失效,需要自己在onMessage里解析更新后的配置文件,再用解析后的值覆盖
14
	@NacosValue(value = "${service001Url:defaultValue}", autoRefreshed = true)
15
    private String service001Url;
16
	@NacosValue(value = "${service001Param:defaultValue}", autoRefreshed = true)
17
    private String service001Param;
18
	
19
	@Bean(name="getService001Url")
20
	public String getService001Url() {
21
		return service001Url;
22
	}
23
	
24
	@Bean(name="getService001Param")
25
	public String getService001Param() {
26
		return service001Param;
27
	}
28
	
29
	@NacosConfigListener(dataId = "myService")
30
	public void onMessage(String config) {
31
	    System.out.println(config);
32
	    //需要自己解析配置文件
33
	}
34
}

+ 0 - 50
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/config/NacosRegisterConfiguration.java

@ -1,50 +0,0 @@
1
package com.ai.ipu.server.config;
2

3
import com.ai.ipu.server.util.IpUtil;
4
import com.alibaba.nacos.api.annotation.NacosInjected;
5
import com.alibaba.nacos.api.naming.NamingService;
6
import com.alibaba.nacos.api.naming.pojo.Instance;
7

8
import org.slf4j.Logger;
9
import org.slf4j.LoggerFactory;
10
import org.springframework.beans.factory.annotation.Value;
11
import org.springframework.context.annotation.Configuration;
12

13
import javax.annotation.PostConstruct;
14

15
@Configuration
16
public class NacosRegisterConfiguration {
17
	private static final Logger log = LoggerFactory.getLogger(NacosRegisterConfiguration.class);
18
	@Value("${server.port}")
19
	private int serverPort;
20

21
	@Value("${spring.application.name}")
22
	private String applicationName;
23

24
	@NacosInjected
25
	private NamingService namingService;
26

27
	@PostConstruct
28
	public void registerInstance() {
29
		try {
30
			//完全自己注册,用于定位问题、解决问题
31
//			Instance instance = new Instance();
32
//			instance.setIp(IpUtil.getHostAddress());//IP
33
//			instance.setPort(serverPort);//端口
34
//			instance.setHealthy(true);//健康状态
35
//			instance.setWeight(1.0);//权重
36
//			instance.setInstanceId(IpUtil.getHostAddress()+"#"+serverPort+"#DEFAULT#DEFAULT_GROUP@@"+applicationName);
37
//			instance.addMetadata("serviceUrl", "/ipu/nacos/discovery/provider/echo");//元数据
38
//			instance.addMetadata("serviceParam", "{message:java.lang.String}");//元数据
39
//			instance.setClusterName("DEFAULT");
40
//			namingService.registerInstance(applicationName, instance);
41
			
42
			//利用nacos自动注册
43
			//ipu-basic里的IpUtil.getInet4Ip()只适用于只有1块网卡的场合
44
			//IpUtil.getHostAddress()在有多块网卡时,取不是.1结尾并且ip地址排序最小的做为当前ip
45
			namingService.registerInstance(applicationName, IpUtil.getHostAddress(), serverPort, "DEFAULT");
46
		} catch (Exception e) {
47
			log.error(e.getMessage());
48
		}
49
	}
50
}

+ 0 - 35
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/control/GracefulTestController.java

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

3
import java.util.concurrent.atomic.AtomicInteger;
4

5
import org.slf4j.Logger;
6
import org.slf4j.LoggerFactory;
7
import org.springframework.stereotype.Controller;
8
import org.springframework.web.bind.annotation.RequestMapping;
9
import org.springframework.web.bind.annotation.ResponseBody;
10

11
@Controller
12
@RequestMapping("/graceful")
13
public class GracefulTestController {
14
	private static final Logger logger = LoggerFactory.getLogger(GracefulTestController.class);
15
	// 计数器
16
	public AtomicInteger started = new AtomicInteger();
17
	public AtomicInteger ended = new AtomicInteger();
18

19
	@RequestMapping("/hello")
20
	@ResponseBody
21
	public String hello() {
22

23
		logger.debug(Thread.currentThread().getName() + " -> " + this + " Get one, got: " + started.addAndGet(1));
24
		try {
25
			Thread.sleep(1000 * 100); // 模拟一个执行时间很长的任务
26
		} catch (InterruptedException e) {
27
			logger.info("模拟任务被中断", e);
28
		}
29

30
		logger.debug(
31
				Thread.currentThread().getName() + " -> " + this + "  Finish one, finished: " + ended.addAndGet(1));
32
		return "hello";
33
	}
34

35
}

+ 0 - 72
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/control/NacosConfigController.java

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

3
import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
4

5
import org.slf4j.Logger;
6
import org.slf4j.LoggerFactory;
7
import org.springframework.stereotype.Controller;
8
import org.springframework.web.bind.annotation.RequestMapping;
9
import org.springframework.web.bind.annotation.ResponseBody;
10

11
import com.ai.ipu.data.JMap;
12
import com.alibaba.nacos.api.annotation.NacosInjected;
13
import com.alibaba.nacos.api.config.ConfigService;
14
import com.alibaba.nacos.api.config.annotation.NacosValue;
15
import com.alibaba.nacos.api.exception.NacosException;
16
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
17
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySources;
18

19
@Controller
20
@RequestMapping("/nacos/config")
21
@NacosPropertySources({
22
@NacosPropertySource(dataId = "mysql", autoRefreshed = true),
23
@NacosPropertySource(dataId = "myService", autoRefreshed = true),
24
@NacosPropertySource(dataId = "myxml", autoRefreshed = true)})
25
public class NacosConfigController {
26
	private static final Logger logger = LoggerFactory.getLogger(NacosConfigController.class);
27
	
28
	//用于发布消息到配置中心
29
	@NacosInjected
30
    private ConfigService configService;
31
	
32
	//如果配置中心没有dataId以及sql的配置,则取defaultValue
33
	//autoRefreshed:是否动态刷新。如果是动态刷新,则配置中心dataId以及sql的配置发生变动,则取配置中心的数据;
34
	//如果不是动态刷新,则在应用启动时去配置中心获取一次dataId以及sql的配置
35
	@NacosValue(value = "${sql001:defaultValue}", autoRefreshed = true)
36
    private String sql;
37
	@NacosValue(value = "${userName:defaultValue}", autoRefreshed = true)
38
    private String userName;
39
	 @ResponseBody
40
	 @RequestMapping("/getSql")
41
	 public String getSql(JMap params) throws Exception {
42
		 return sql;
43
	 }
44
	 
45
	 @ResponseBody
46
	 @RequestMapping("/setSql")
47
	 public boolean setSql(JMap params) throws Exception {
48
		 try {
49
			    //将select * from display.tab_page_info发布到配置中心,dataId=com.ai.ipu.nacos,变量名=sql
50
	            configService.publishConfig("mysql", DEFAULT_GROUP, "sql001 = select * from display.tab_page_info\nuserName = david");
51
	            return true;
52
	        } catch (NacosException e) {
53
//	            e.printStackTrace();
54
	        	logger.error("发布数据到配置中心失败", e);
55
	            return false;
56
	        }
57
	 }
58
	 /* 用于测试热加载 
59
	 @ResponseBody
60
	 @RequestMapping("/removeSql")
61
	 public boolean removeSql(JMap params) throws Exception {
62
		 try {
63
			    //从配置中心删除配置,dataId=sql
64
	            configService.removeConfig("sql", DEFAULT_GROUP);
65
	            return true;
66
	        } catch (NacosException e) {
67
	            logger.error("从配置中心删除配置失败", e);
68
	            return false;
69
	        }
70
	 }*/
71
	 
72
}

+ 0 - 97
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/control/NacosConsumerControl.java

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

3
import org.slf4j.Logger;
4
import org.slf4j.LoggerFactory;
5
import org.springframework.beans.factory.annotation.Autowired;
6
import org.springframework.beans.factory.annotation.Value;
7
import org.springframework.http.ResponseEntity;
8
import org.springframework.stereotype.Controller;
9
import org.springframework.web.bind.annotation.GetMapping;
10
import org.springframework.web.bind.annotation.RequestMapping;
11
import org.springframework.web.bind.annotation.ResponseBody;
12
import org.springframework.web.client.RestTemplate;
13

14
import com.ai.ipu.server.config.NacosConfig;
15
import com.alibaba.nacos.api.annotation.NacosInjected;
16
import com.alibaba.nacos.api.config.annotation.NacosValue;
17
import com.alibaba.nacos.api.exception.NacosException;
18
import com.alibaba.nacos.api.naming.NamingService;
19
import com.alibaba.nacos.api.naming.pojo.Instance;
20
@Controller
21
@RequestMapping("/nacos/discovery/consumer")
22
public class NacosConsumerControl {
23
	private static final Logger logger = LoggerFactory.getLogger(NacosConsumerControl.class);
24
	
25
	@NacosInjected
26
    private NamingService namingService;
27
	private RestTemplate restTemplate = new RestTemplate();
28
	
29
	@Value("${spring.application.name}")
30
    private String appName;
31
	@ResponseBody
32
    @GetMapping(value = "/echo")
33
    public String echo() throws NacosException {
34
		try {
35
			if (namingService != null) {
36
				// 选择user_service服务的一个健康的实例(可配置负载均衡策略)
37
				Instance instance = namingService.selectOneHealthyInstance("ipu-rest-scaffold");
38
				// 拼接请求接口url并请求选取的实例
39
				String url = "http://" + instance.getIp() + ":" + instance.getPort() + "/ipu/nacos/discovery/provider/echo?message=" + appName;
40
				logger.debug(String.format("请求URL:%s", url));
41
				ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
42
				logger.debug(String.format("响应结果:%s", entity.getBody()));
43
				return entity.getBody();
44
			}
45
		} catch (Exception e) {
46
			logger.error("get instance from nacos error", e);
47
		}
48
        return null;
49
    }
50
	
51

52
	@NacosValue(value = "${service001Url:defaultValue}", autoRefreshed = true)
53
    private String service001Url;
54
	@NacosValue(value = "${service001Param:defaultValue}", autoRefreshed = true)
55
    private String service001Param;
56
	@ResponseBody
57
    @GetMapping(value = "/service001")
58
    public String service001() throws NacosException {
59
		try {
60
			if (namingService != null) {
61
				// 选择user_service服务的一个健康的实例(可配置负载均衡策略)
62
				Instance instance = namingService.selectOneHealthyInstance("ipu-rest-scaffold");
63
				// 拼接请求接口url并请求选取的实例
64
				String url = "http://" + instance.getIp() + ":" + instance.getPort() + service001Url + "?message=" + appName;
65
				logger.debug(String.format("请求URL:%s", url));
66
				ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
67
				logger.debug(String.format("响应结果:%s", entity.getBody()));
68
				return entity.getBody();
69
			}
70
		} catch (Exception e) {
71
			logger.error("get instance from nacos error", e);
72
		}
73
        return null;
74
    }
75
	@Autowired
76
	NacosConfig config;
77
	@ResponseBody
78
    @GetMapping(value = "/service001test")
79
    public String service001test() throws NacosException {
80
		try {
81
			if (namingService != null) {
82
				// 选择user_service服务的一个健康的实例(可配置负载均衡策略)
83
				Instance instance = namingService.selectOneHealthyInstance("ipu-rest-scaffold");
84
				// 拼接请求接口url并请求选取的实例
85
				String url = "http://" + instance.getIp() + ":" + instance.getPort() + config.getService001Url() + "?message=" + appName;
86
				logger.debug(String.format("请求URL:%s", url));
87
				ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
88
				logger.debug(String.format("响应结果:%s", entity.getBody()));
89
				return entity.getBody();
90
			}
91
		} catch (Exception e) {
92
			logger.error("get instance from nacos error", e);
93
		}
94
        return null;
95
    }
96
	
97
}

+ 0 - 19
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/control/NacosProviderControl.java

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

3

4
import org.springframework.stereotype.Controller;
5
import org.springframework.web.bind.annotation.GetMapping;
6
import org.springframework.web.bind.annotation.RequestMapping;
7
import org.springframework.web.bind.annotation.ResponseBody;
8

9
@Controller
10
@RequestMapping("/nacos/discovery/provider")
11
public class NacosProviderControl {
12

13
    @ResponseBody
14
	@GetMapping(value = "/echo")
15
    public String hello(String message) {
16
        return "Hello Nacos " + message;
17
    }
18
	
19
}

+ 3 - 1
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/util/SpringUtil.java

@ -22,7 +22,9 @@ public class SpringUtil implements ApplicationContextAware {
22 22
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
23 23
    	setApplicationcontext(applicationContext);
24 24
        logger.debug("---------------------------------------------------------------------");
25
        logger.debug("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringUtil.applicationContext+"========");
25
        logger.debug("ApplicationContext配置成功");
26
        logger.debug("可以通过调用SpringUtils.getAppContext()获取applicationContext对象");
27
        logger.debug("applicationContext=" + SpringUtil.applicationContext);
26 28
        logger.debug("---------------------------------------------------------------------");
27 29
    }
28 30


+ 6 - 60
ipu-rest-scaffold/src/main/resources/dev/application.properties

@ -1,5 +1,5 @@
1
######设置服务器端口
2
######也可以通过启动命令行参数实现:java -jar myproject.jar --server.port=9084
1
#设置服务器端口
2
#也可以通过启动命令行参数实现:java -jar myproject.jar --server.port=9084
3 3
server.port=unknown
4 4

5 5
web.root=webapp/
@ -8,70 +8,16 @@ spring.mvc.static-path-pattern=/**
8 8
#spring.resources.static-locations=file:${web.root}
9 9
spring.resources.static-locations=classpath:/${web.root}
10 10

11
######context-path默认/
11
#context-path默认/
12 12
server.context-path=/ipu
13
######注册DispatcherServlet对应path,亦可通过dispatcherRegistration方法配置
13
#注册DispatcherServlet对应path,亦可通过dispatcherRegistration方法配置
14 14
#server.servlet-path=/ipu1
15 15
#使用maven中的变量替换
16 16
logging.file=target/logs/${project.artifactId}.log
17 17
spring.application.name=${project.artifactId}
18 18

19
######查看spring错误日志
19
#查看spring错误日志
20 20
#logging.level.org.springframework=DEBUG
21 21

22
######session使用默认
22
#session使用默认
23 23
spring.session.store-type=none
24

25
#启用shutdown
26
endpoints.shutdown.enabled=true
27
#禁用密码验证
28
endpoints.shutdown.sensitive=false
29
# 自定义管理端点的前缀(保证安全)
30
management.context-path=/MyActuator
31
# 指定管理端口
32
management.port=12581
33
# 不允许远程管理连接(不允许外部调用保证安全)
34
management.address=127.0.0.1
35
#管理安全设置,不推荐设置为false,缺省为true
36
#false表示允许任何人访问管理节点
37
#true则只允许指定用户密码才能访问
38
management.security.enabled=false
39

40
###配置nacos配置中心
41
nacos.config.server-addr=10.1.236.121:8848,10.1.236.121:8849,10.1.236.121:8850
42

43
#nacos.config.shared-dataids=mysqlConfig, example
44
#nacos.config.refreshable-dataids=mysqlConfig, example
45
# 主配置 group-id
46
#nacos.config.group=DEFAULT_GROUP
47
# 主配置 配置文件类型
48
#nacos.config.type=properties
49
# 主配置 最大重试次数
50
#nacos.config.max-retry=10
51
# 主配置 开启自动刷新
52
#nacos.config.auto-refresh=true
53
# 主配置 重试时间
54
#nacos.config.config-retry-time=2333
55
# 主配置 配置监听长轮询超时时间
56
#nacos.config.config-long-poll-timeout=46000
57
# 主配置 开启注册监听器预加载配置服务(除非特殊业务需求,否则不推荐打开该参数)
58
#nacos.config.enable-remote-sync-config=false
59

60
nacos.config.ext-config[0].data-id=mysqlConfig
61
nacos.config.ext-config[0].group=DEFAULT_GROUP
62
nacos.config.ext-config[0].refresh=true
63
nacos.config.ext-config[1].data-id=example
64
nacos.config.ext-config[1].group=DEFAULT_GROUP
65
nacos.config.ext-config[1].refresh=true
66

67

68
###配置nacos注册中心
69
nacos.discovery.server-addr=10.1.236.121:8848,10.1.236.121:8849,10.1.236.121:8850
70

71
#设置开启热部署
72
spring.devtools.restart.enabled=true
73
#重启目录
74
spring.devtools.restart.additional-paths=src/main/java
75
spring.devtools.restart.exclude=WEB-INF/**
76
#页面热加载
77
spring.freemarker.cache=false 

+ 0 - 3
ipu-rest-scaffold/src/main/resources/ipu-spring-mvc.xml

@ -11,7 +11,4 @@
11 11
		http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
12 12

13 13
    <context:component-scan base-package="com.ai.ipu.server" />
14
	<aop:aspectj-autoproxy proxy-target-class="true"/>
15
	<context:annotation-config />
16
	<bean id="transcationAspects" class="com.ai.ipu.nosql.aspect.TransactionAspect" />
17 14
</beans>