获取网络上下行速度、判断nginx是否运行、检查网络端口是否通、执行ssh连接工具、注解方式分布式锁

一、获取网络上下行速度

import cn.hutool.core.date.DateUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class NetWorkUtil {
     

	private static final int SLEEP_TIME = 2 * 1000;

	// 获取网络上行下行速度
	public static NetworkInfo getNetworkDownUp() {
     
		Properties props = System.getProperties();
		String os = props.getProperty("os.name").toLowerCase();
		os = os.startsWith("win") ? "windows" : "linux";
		Process pro = null;
		Runtime r = Runtime.getRuntime();
		BufferedReader input = null;
		NetworkInfo networkInfo = new NetworkInfo();

		try {
     
			String command = "windows".equals(os) ? "netstat -e" : "ifconfig";
			pro = r.exec(command);
			input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			long result1[] = readInLine(input, os);
			Thread.sleep(SLEEP_TIME);
			pro.destroy();
			input.close();
			pro = r.exec(command);
			input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			long result2[] = readInLine(input, os);
            // 上行速率(kB/s)
			networkInfo.setReceive(formatNumber((result2[0] - result1[0]) / (1024.0 * (SLEEP_TIME / 1000))));
            // 下行速率(kB/s)
			networkInfo.setSend(formatNumber((result2[1] - result1[1]) / (1024.0 * (SLEEP_TIME / 1000))));
			// 去绝对值
			if (networkInfo.getReceive() < 0) {
     
				networkInfo.setReceive(0 - networkInfo.getReceive());
			}
			if (networkInfo.getSend() < 0) {
     
				networkInfo.setSend(0 - networkInfo.getSend());
			}
		} catch (Exception e) {
     
			e.printStackTrace();
		} finally {
     
			if (input != null) {
     
				try {
     
					input.close();
				} catch (IOException e) {
     
					log.error("获取失败:{}",e)
				}
			}
			Optional.ofNullable(pro).ifPresent(p -> p.destroy());
		}
		networkInfo.setTime(DateUtil.format(new Date(), "HH:mm:ss"));
		return networkInfo;

	}

	private static long[] readInLine(BufferedReader input, String osType) {
     
		long arr[] = new long[2];
		StringTokenizer tokenStat;
		try {
     
            // 获取linux环境下的网口上下行速率
			if (Objects.equals(osType, "linux")) {
     
				long rx = 0, tx = 0;
				String line;
				// 旧
				// RX packets:4171603 errors:0 dropped:0 overruns:0 frame:0
				// TX packets:4171603 errors:0 dropped:0 overruns:0 carrier:0
				// 新
				// RX packets 228451110  bytes 153707332334 (153.7 GB)
				// TX packets 169848511  bytes 155937621328 (155.9 GB)
				while ((line = input.readLine()) != null) {
     
					if (line.indexOf("RX packets") >= 0) {
     
						rx += Long.parseLong(line.split("packets")[1].split("bytes")[0].trim()) * 1024;
					} else if (line.indexOf("TX packets") >= 0) {
     
						tx += Long.parseLong(line.split("packets")[1].split("bytes")[0].trim()) * 1024;
					}
				}
				arr[0] = rx;
				arr[1] = tx;
			} else {
      // 获取windows环境下的网口上下行速率
				input.readLine();
				input.readLine();
				input.readLine();
				input.readLine();
				tokenStat = new StringTokenizer(input.readLine());
				tokenStat.nextToken();
				arr[0] = Long.parseLong(tokenStat.nextToken());
				arr[1] = Long.parseLong(tokenStat.nextToken());
			}
		} catch (Exception e) {
     
			log.error("获取失败:{}",e)
		}
		return arr;
	}

	private static Double formatNumber(double f) {
     
		return Double.parseDouble(new Formatter().format("%.2f", f).toString());
	}

	public static void main(String[] args) {
     
		String line = "      RX packets 0  bytes 0 (0.0 B)";
		System.out.println(Long.parseLong(line.split("packets")[1].split("bytes")[0].trim()));
	}


    static class NetworkInfo {
     

        Double send;

        Double receive;

        String time;

        public String getTime() {
     
            return time;
        }

        public void setTime(String time) {
     
            this.time = time;
        }

        public Double getSend() {
     
            return send;
        }

        public void setSend(Double send) {
     
            this.send = send;
        }

        public Double getReceive() {
     
            return receive;
        }

        public void setReceive(Double receive) {
     
            this.receive = receive;
        }

    }
}
import cn.hutool.system.SystemUtil;

public class SystemTool {
     

	public static String getSystem() {
     

		if (SystemUtil.get(SystemUtil.OS_NAME).toLowerCase().contains("windows")) {
     
			return "Windows";
		} else if (SystemUtil.get(SystemUtil.OS_NAME).toLowerCase().contains("mac os")) {
     
			return "Mac OS";
		} else {
     
			return "Linux";
		}

	}

	public static Boolean isWindows() {
     
		return getSystem().equals("Windows");
	}

	public static Boolean isMacOS() {
     
		return getSystem().equals("Mac OS");
	}

	public static Boolean isLinux() {
     
		return getSystem().equals("Linux");
	}

	public static boolean hasRoot() {
     
		if (SystemTool.isLinux()) {
     
			String user = System.getProperties().getProperty(SystemUtil.USER_NAME);
			if ("root".equals(user)) {
     
				return true;
			} else {
     
				return false;
			}
		}
		return true;
	}

}

二、判断nginx是否运行

import cn.hutool.core.util.RuntimeUtil;

public class NginxUtils {
     

	/**
	 * 判断nginx是否运行
	 * 
	 * @return
	 */
	public static boolean isRun() {
     
		boolean isRun = false;
		if (SystemTool.isWindows()) {
     
			String[] command = {
      "tasklist" };
			String rs = RuntimeUtil.execForStr(command);
			isRun = rs.toLowerCase().contains("nginx.exe");
		} else {
     
			String[] command = {
      "/bin/sh", "-c", "ps -ef|grep nginx" };
			String rs = RuntimeUtil.execForStr(command);
			isRun = rs.contains("nginx: master process") || rs.contains("nginx: worker process");
		}

		return isRun;
	}
}

三、检查网络端口是否通

import java.io.IOException;
import java.net.*;

/**
 * @author nick
 */
public class TelnetUtils {
     
	public static boolean isRunning(String host, int port) {
     
		Socket sClient = null;
		try {
     
			SocketAddress saAdd = new InetSocketAddress(host.trim(), port);
			sClient = new Socket();
			// 设置超时 1s
			sClient.connect(saAdd, 1000);
		} catch (UnknownHostException | SocketTimeoutException e) {
     
			return false;
		} catch (IOException e) {
     
			return false;
		} catch (Exception e) {
     
			return false;
		} finally {
     
			try {
     
				if (sClient != null) {
     
					sClient.close();
				}
			} catch (Exception e) {
     
			}
		}
		return true;
	}

	public static void main(String[] args) {
     
		System.out.println( isRunning("127.0.0.1", 8080));
	}
}

四、执行ssh连接工具

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

@Slf4j
public class SSHClientUtils {
     

	public static class MyUserInfo implements UserInfo {
     

		private String password;

		@Override
		public String getPassphrase() {
     
			return null;
		}

		@Override
		public String getPassword() {
     
			return password;
		}

		@Override
		public boolean promptPassword(String message) {
     
			return true;
		}

		@Override
		public boolean promptPassphrase(String message) {
     
			return true;
		}

		@Override
		public boolean promptYesNo(String message) {
     
			return true;
		}

		@Override
		public void showMessage(String message) {
     
			log.info(message);
		}

		public void setPassword(String password) {
     
			this.password = password;
		}

	}

	/**
	 * 直接执行命令
	 */
	public static String exec(Ssh ssh, String cmd) {
     
		JSch jsch = new JSch();
		String outStr = "";
		try {
     
			Session session = jsch.getSession(ssh.getUsername(), ssh.getHost(), ssh.getPort());
			MyUserInfo ui = new MyUserInfo();
			ui.setPassword(ssh.getPassword());
			session.setUserInfo(ui);
			session.connect();
			Channel channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand(cmd);
			InputStream in = channel.getInputStream();
			OutputStream out = channel.getOutputStream();
			((ChannelExec) channel).setErrStream(System.err);
			channel.connect();
			out.flush();
			outStr = IOUtils.toString(in, Charset.forName("utf-8"));
			log.info(outStr);
			channel.disconnect();
			session.disconnect();
		} catch (Exception e) {
     
            log.error("出现异常:{}",e);
		}
		return outStr;
	}


	class Ssh{
     

		private String name;
		private String host;
		private Integer port;
		private String username;
		private String password;

		public String getName() {
     
			return name;
		}

		public void setName(String name) {
     
			this.name = name;
		}

		public String getHost() {
     
			return host;
		}

		public void setHost(String host) {
     
			this.host = host;
		}

		public Integer getPort() {
     
			return port;
		}

		public void setPort(Integer port) {
     
			this.port = port;
		}

		public String getUsername() {
     
			return username;
		}

		public void setUsername(String username) {
     
			this.username = username;
		}

		public String getPassword() {
     
			return password;
		}

		public void setPassword(String password) {
     
			this.password = password;
		}
	}

}

五、注解方式分布式锁

import java.lang.annotation.*;


@Target({
     ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RedisLock {
     
}

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;
import java.util.Optional;


@Aspect
@Slf4j
public class RedisLockAspect {
     

    private StringRedisTemplate redisTemplate;
    @Value("${common-mq.redis-lock.namespace:#{'common-mq:${spring.application.name:unknown-service-name}:'}}")
    private String namespace;

    public RedisLockAspect(StringRedisTemplate redisTemplate) {
     
        this.redisTemplate = redisTemplate;
    }

    @Pointcut("@within(redisLock) || @annotation(redisLock)")
    public void joinPoint(RedisLock redisLock) {
     
    }

    @Around(value = "joinPoint(redisLock)", argNames = "pjp,redisLock")
    public final Object doAround(final ProceedingJoinPoint pjp, RedisLock redisLock) throws Throwable {
     
        Boolean success =
                Optional.ofNullable(redisTemplate.opsForValue().setIfAbsent(getKey(pjp),
                        Thread.currentThread().getName(), Duration.ofMinutes(1))).orElse(false);
        if (success) {
     
            try {
     
                return pjp.proceed();
            } finally {
     
                redisTemplate.delete(getKey(pjp));
            }
        }
        return null;
    }

    protected String getKey(ProceedingJoinPoint pjp) {
     
        return namespace + pjp.toString();
    }

}
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;


@Configuration
@ConditionalOnClass(RedisTemplate.class)
public class RedisLockConfiguration {
     

    @Bean
    @ConditionalOnMissingBean
    public RedisLockAspect redisLockAspect(ObjectProvider<StringRedisTemplate> redisTemplates) {
     
        StringRedisTemplate redisTemplate = redisTemplates.getIfUnique();
        return redisTemplate == null ? null : new RedisLockAspect(redisTemplate);
    }

}

你可能感兴趣的:(JAVA开发,获取网络上下行速度,注解方式分布式锁,判断nginx是否运行,执行ssh连接工具,检查网络端口是否通)