Commit 90722cb6 by giaogiao

添加nacos注册中心

parent e9515c48
......@@ -16,36 +16,58 @@
package io.geekidea.springbootplus;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosWatch;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.wecloud.im.register.GetIpUtils;
import io.geekidea.springbootplus.framework.util.PrintApplicationInfo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* spring-boot-plus 项目启动入口
*
* @author geekidea
* @since 2018-11-08
*/
@EnableDiscoveryClient
@EnableAsync
@EnableScheduling
@EnableTransactionManagement
@EnableConfigurationProperties
@ServletComponentScan
@EnableCaching
@ConfigurationPropertiesScan("com.wecloud.im.config")
//@ConfigurationPropertiesScan("com.wecloud.im")
@MapperScan({"io.geekidea.springbootplus.**.mapper", "com.wecloud.**.mapper"})
@SpringBootApplication(scanBasePackages = {"io.geekidea.springbootplus", "com.wecloud", "com.wecloud.im", "com.wecloud.im.config"})
@SpringBootApplication(scanBasePackages = {"io.geekidea.springbootplus", "com.wecloud"})
public class SpringBootPlusApplication {
@Value("${netty.port}")
private String nettyPort;
@Resource
private GetIpUtils getIpUtils;
public static void main(String[] args) {
// 启动spring-boot-plus
......@@ -56,4 +78,35 @@ public class SpringBootPlusApplication {
PrintApplicationInfo.printTip(context);
}
@Bean
@ConditionalOnMissingBean
public NacosDiscoveryProperties nacosProperties() {
return new NacosDiscoveryProperties();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = {"spring.cloud.nacos.discovery.watch.enabled"}, matchIfMissing = true)
public NacosWatch nacosWatch(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties, ObjectProvider<ThreadPoolTaskScheduler> taskScheduler) {
Map<String, String> metadataMap = nacosDiscoveryProperties.getMetadata();
if (metadataMap == null) {
metadataMap = new HashMap<>();
}
String key = "ip.netty.public";
metadataMap.put("startup.time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
String value = getIpUtils.getPublicIp() + ":" + nettyPort;
metadataMap.put(key, value);
// 设置心跳的周期,单位为秒,这里将心跳间隔设置为3秒:
metadataMap.put(PreservedMetadataKeys.HEART_BEAT_INTERVAL, "3000");
// 设置心跳超时时间,单位为秒,这里将心跳超时时间设为6秒,
// 即服务端6秒收不到客户端心跳,会将该客户端注册的实例设为不健康:
metadataMap.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "6000");
// 设置实例删除的超时时间,单位为秒,这里将实例删除超时时间设为9秒,
// 即服务端9秒收不到客户端心跳,会将该客户端注册的实例删除:
metadataMap.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "9000");
nacosDiscoveryProperties.setMetadata(metadataMap);
return new NacosWatch(nacosServiceManager, nacosDiscoveryProperties, taskScheduler);
}
}
/*
* Copyright 2019-2029 geekidea(https://github.com/geekidea)
*
* 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 io.geekidea.springbootplus.test;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.wecloud.im.register.GetIpUtils;
import io.geekidea.springbootplus.SpringBootPlusApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
/**
* get ip
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootPlusApplication.class)
public class GetIpTest {
@Autowired
private GetIpUtils publicIpUtils;
@Value("${spring.cloud.nacos.discovery.server-addr}")
private String addr;
@Test
public void test() throws NacosException {
// String s = publicIpUtils.getlanIp();
// String publicIp = publicIpUtils.getPublicIp();
// String s2 = publicIpUtils.getlanIp();
// String publicIp2 = publicIpUtils.getPublicIp();
// String serveAddr = System.getProperty("serveAddr");
NamingService naming = NamingFactory.createNamingService(addr);
Instance wecloudIm = naming.selectOneHealthyInstance("wecloud_im");
Map<String, String> metadata = wecloudIm.getMetadata();
String publicIp = metadata.get("ip.netty.public");
System.out.println(wecloudIm);
// naming.subscribe("ip.netty.public", event -> {
// if (event instanceof NamingEvent) {
// System.out.println(((NamingEvent) event).getServiceName());
// System.out.println(((NamingEvent) event).getInstances());
// }
// });
// while (true){
//
// }
}
}
......@@ -13,7 +13,7 @@
<artifactId>common</artifactId>
<name>common</name>
<description>api服务模块</description>
<description>应用服务模块</description>
<dependencies>
<dependency>
......@@ -21,6 +21,11 @@
<artifactId>framework</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.firebase</groupId>
......@@ -69,18 +74,6 @@
<!-- netty-->
<!-- 公众号(包括订阅号和服务号):weixin-java-mp -->
<!-- <dependency>-->
<!-- <groupId>com.github.binarywang</groupId>-->
<!-- <artifactId>weixin-java-mp</artifactId>-->
<!-- <version>4.0.0</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.github.binarywang</groupId>-->
<!-- <artifactId>weixin-java-pay</artifactId>-->
<!-- <version>4.0.0</version>-->
<!-- </dependency>-->
<!-- fastbootWeixin的核心依赖 -->
......
package com.wecloud.im.register;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* 获取公网ip
*/
@Component
@Slf4j
public class GetIpUtils {
private static final String LOCAL = "local";
private static final String AWS = "aws";
private static final String HUAWEI_CLOUD = "huawei";
/**
* 内网ip
*/
private static String lAN_IP = null;
/**
* 公网ip
*/
private static String PUBLIC_IP = null;
/**
* 服务器运营商local,aws,huawei
*/
@Value("${load-blance.server-type}")
private String SERVER_TYPE;
/**
* 内网ip
*
* @return
*/
public String getlanIp() {
if (lAN_IP == null) {
lAN_IP = getLocalIpAddress();
}
return lAN_IP;
}
/**
* 公网ip
*/
public String getPublicIp() {
if (PUBLIC_IP == null) {
switch (SERVER_TYPE) {
case LOCAL:
PUBLIC_IP = getlanIp();
break;
case AWS:
PUBLIC_IP = HttpUtil.get("http://instance-data/latest/meta-data/public-ipv4", 30);
break;
case HUAWEI_CLOUD:
PUBLIC_IP = HttpUtil.get("http://169.254.169.254/latest/meta-data/public-ipv4", 30);
break;
}
}
return PUBLIC_IP;
}
/**
* 判断是否为虚拟mac地址
*
* @param mac
* @return
*/
private static boolean isVmMac(byte[] mac) {
if (null == mac) {
return false;
}
/*
* 排除无效的mac地址
*/
byte[][] INVALID_MACS = {
{0x00, 0x05, 0x69}, // VMWare
{0x00, 0x1C, 0x14}, // VMWare
{0x00, 0x0C, 0x29}, // VMWare
{0x00, 0x50, 0x56}, // VMWare
{0x08, 0x00, 0x27}, // Virtualbox
{0x0A, 0x00, 0x27}, // Virtualbox
{0x00, 0x03, (byte) 0xFF}, // Virtual-PC
{0x00, 0x15, 0x5D} // Hyper-V
};
for (byte[] invalid : INVALID_MACS) {
if (invalid[0] == mac[0] && invalid[1] == mac[1] && invalid[2] == mac[2]) {
return true;
}
}
return false;
}
/**
* 获取本机地址
*/
private static String getLocalIpAddress() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = networkInterfaces.nextElement();
/*
排除docker虚拟网卡
*/
String docker0 = "docker0";
if (ni.getName().equals(docker0)) {
continue;
}
if (!ni.isUp() || ni.isLoopback() || ni.isVirtual()) {
continue;
}
if (isVmMac(ni.getHardwareAddress())) {
continue;
}
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (inetAddress.isLinkLocalAddress()) {
continue;
}
return inetAddress.getHostAddress();
}
}
} catch (SocketException e) {
log.info("获取本机IP地址失败。" + e);
}
return StringUtils.EMPTY;
}
}
......@@ -26,8 +26,17 @@ spring:
password:
port: 6379
cloud:
nacos:
discovery:
server-addr: localhost:8848
# 打印SQL语句和结果集,本地开发环境可开启,线上注释掉
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 服务器负载均衡配置
load-blance:
# 服务器运营商local,aws,huawei
server-type: local
......@@ -26,11 +26,20 @@ spring:
host: 172.31.38.183
password: qZ8yzTz8chSZE1ZbbRbK
port: 6379
cloud:
nacos:
discovery:
server-addr: localhost:8848
# knife4j配置
knife4j:
enable: ${spring-boot-plus.swagger.enable}
basic:
enable: true
username: 321wecloudAdmin123
password: hj12ad2f123H22skd3123sk2h
\ No newline at end of file
password: hj12ad2f123H22skd3123sk2h
# 服务器负载均衡配置
load-blance:
# 服务器运营商local,aws,huawei
server-type: aws
......@@ -26,9 +26,17 @@ spring:
host: 127.0.0.1
password: JH86uc53r8Ca
port: 6379
cloud:
nacos:
discovery:
server-addr: localhost:8848
# 打印SQL语句和结果集,本地开发环境可开启,线上注释掉
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 服务器负载均衡配置
load-blance:
# 服务器运营商local,aws,huawei
server-type: aws
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment