目录
小程序解密
// 被加密的数据
// byte[] dataByte = java.util.Base64.getDecoder().decode(data);
// // 加密秘钥
// byte[] keyByte = java.util.Base64.getDecoder().decode(key);
// // 偏移量
// byte[] ivByte = Base64.getDecoder().decode(iv);
// try {
// int base = 16;
// if (keyByte.length % base != 0) {
// int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
// byte[] temp = new byte[groups * base];
// Arrays.fill(temp, (byte) 0);
// System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
// keyByte = temp;
// }
// Security.addProvider(new BouncyCastleProvider());
// Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
// AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
// parameters.init(new IvParameterSpec(ivByte));
// cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
// String json;
// byte[] resultByte = cipher.doFinal(dataByte);
// if (null != resultByte && resultByte.length > 0) {
// String result = new String(resultByte, "UTF-8");
// json = JSON.toJSONString(JSONObject.parseObject(result));
// //没有插入数据库
// return json;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
查询数据 分组
List<ExChange> records = exchangeRecordMapper.selectAllPatExchangeRecordByUser(userId);
//按年月分组
records.stream()
.collect(Collectors.groupingBy(e -> e.getChangeTime().getYear() + "年" + e.getChangeTime().getMonthValue() + "月",LinkedMap::new,Collectors.toList()))
SQL
查询前三并添加序号
SELECT
@rank := @rank + 1 AS rank_no,
a.*
FROM
( SELECT * FROM `pat_wechat_personnel` ORDER BY integral DESC limit 3) a,
( SELECT @rank := 0 ) b
Oss
private static final Logger logger = LoggerFactory.getLogger(OssUtil.class);
/**
* 访问账号key
*/
private String accessKeyId = "";
/**
* 访问秘钥
*/
private String accessKeySecret = "";
/**
* 地域节点
*/
private String endpoint = "";
/**
* 存储桶名
*/
private String bucket = "";
/**
* bucket 域名
*/
private String publicAccessUrl = "";
public String getPublicAccessUrl() {
return publicAccessUrl;
}
public void setPublicAccessUrl(String publicAccessUrl) {
this.publicAccessUrl = publicAccessUrl;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
// public static final String SUGE__OSS = "suge/";
public static final String SUGE__OSS = "patfile/";
public static String getContentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
return "image/bmp";
}
if (FilenameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (FilenameExtension.equalsIgnoreCase(".html")) {
return "text/html";
}
if (FilenameExtension.equalsIgnoreCase(".txt")) {
return "text/plain";
}
if (FilenameExtension.equalsIgnoreCase(".vsd")) {
return "application/vnd.visio";
}
if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg") || FilenameExtension.equalsIgnoreCase(".png")) {
return "image/jpg";
}
if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) {
return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) {
return "application/msword";
}
if (FilenameExtension.equalsIgnoreCase(".pdf")) {
return "application/pdf";
}
if (FilenameExtension.equalsIgnoreCase(".xla") ||
FilenameExtension.equalsIgnoreCase(".xlc") ||
FilenameExtension.equalsIgnoreCase(".xlm") ||
FilenameExtension.equalsIgnoreCase(".xls") ||
FilenameExtension.equalsIgnoreCase(".xlt") ||
FilenameExtension.equalsIgnoreCase(".xlw")) {
return "application/vnd.ms-excel";
}
if (FilenameExtension.equalsIgnoreCase(".xml")) {
return "text/xml";
}
if (FilenameExtension.equalsIgnoreCase(".avi")) {
return "video/avi";
}
if (FilenameExtension.equalsIgnoreCase(".mp4")) {
return "video/mp4";
}
if (FilenameExtension.equalsIgnoreCase(".mp3")) {
return "audio/mp3";
}
return "application/octet-stream";
}
public String[] upload(String path, MultipartFile[] files) throws IOException {
logger.info("------OSS文件上传开始--------" + files.length);
String[] strings = new String[files.length];
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
for (int i = 0; i < files.length; i++) {
Date date = new Date();
SimpleDateFormat dateFormatformat = new SimpleDateFormat("yyyy/MM/dd/HH:mm:ss");
String format1 = dateFormatformat.format(date);
String generateUploadPath = path + format1 + "/" + files[i].getOriginalFilename();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, generateUploadPath, files[i].getInputStream());
// strings[i] = getPublicAccessUrl() + "/" + generateUploadPath;
ObjectMetadata metadata = new ObjectMetadata();
//拿到后缀,设置type
metadata.setContentType(getContentType(files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf("."))));
System.out.println(files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf(".")));
putObjectRequest.setMetadata(metadata);
ossClient.putObject(putObjectRequest);
strings[i] = getPublicAccessUrl() + "/" + generateUploadPath;
}
ossClient.shutdown();
return strings;
}
public void delete(String[] strings) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ArrayList<String> objects = new ArrayList<>();
for (int i = 0; i < strings.length; i++) {
objects.add(strings[i]);
}
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucket).withKeys(objects));
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
ossClient.shutdown();
}
序列化
ObjectOutputStream负责把一个Java对象写入二进制流
try(ObjectOutputStream output = new ObjectOutputStream(...)){
output.writeobject(new Person("xiao Ming"));
output.writeobject(new Person("xiao Hing"));
}
ObjectInputStream负责把一个Java对象写入二进制流
try(ObjectInputStream output = new ObjectInputStream(...)){
Object p1 =input.readObject();
Person p2 = (Person) input.readObjecg();
}
List元素替换
/**
* 功能描述:list元素替换
*
* @Author: suge
* @Date: 2021/11/13 14:39
**/
public class Swap {
public static <T> void swa(List<T> list,int old,int newPosition){
if(null == list){
throw new IllegalStateException("list不能为空");
}
T t = list.get(old);
if(old<newPosition){
for(int i = old; i < newPosition; i++){
list.set(i, list.get(i + 1));
}
list.set(newPosition, t);
}
}
}
String 十六进制转换
public class ChineseHex {
public static String toChineseHex(String s)
{
String ss = s;
byte[] bt = ss.getBytes();
String s1 = "";
for (int i = 0; i < bt.length; i++)
{
String tempStr = Integer.toHexString(bt[i]);
if (tempStr.length() > 2)
tempStr = tempStr.substring(tempStr.length() - 2);
s1 = s1 + tempStr + " ";
}
return s1.toUpperCase();
}
}
多个空格变为1个空格
String i = "1 2 3 4 ";
i = i.replaceAll(" + ", " ");
System.out.println(i);
参数拼装、过滤请求
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray) {
StringBuilder paramStr = new StringBuilder();
if (paramsArray != null) {
for (Object param : paramsArray) {
if (param != null) {
if(param instanceof ServletRequest
|| param instanceof ServletResponse
|| param instanceof MultipartFile
|| param instanceof MultipartRequest
){
continue;
}
if (!isFilterObject(param))
{
Object jsonObj = JSON.toJSON(param);
paramStr.append(jsonObj.toString());
}
}
}
}
return paramStr.toString();
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o) {
Class<?> clazz = o.getClass();
if (clazz.isArray()) {
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
} else if (Collection.class.isAssignableFrom(clazz)) {
Collection collection = (Collection) o;
for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
return iter.next() instanceof MultipartFile;
}
} else if (Map.class.isAssignableFrom(clazz)) {
Map map = (Map) o;
for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
}
steam去重
public class StreamDemo {
public static void main(String[] args) {
Student student1 = new Student(11,"a1",22);
Student student2 = new Student(11,"a2",23);
Student student3 = new Student(12,"a2",24);
Student student5 = new Student(16,"a5",26);
Student student4 = new Student(14,"a4",24);
List<Student> students = Arrays.asList(student2, student1, student3, student4,student5);
//对象去重
students.stream().distinct().collect(Collectors.toList()).forEach(System.out::println);
System.out.println("--------------------");
//属性去重
students.stream().filter(distinctByKey(Student::getUserName)).forEach(System.out::println);
System.out.println("--------------------");
//根据属性排序
students.stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println);
students.stream().filter(t->{
return t.getId()%2 == 0;
}).filter(u->{return u.getAge() > 22; }).map(m->{return m.getUserName().toUpperCase();}).sorted(Comparator.reverseOrder()).forEach(System.out::println);
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
树形结构
import java.util.*;
import java.util.stream.Collectors;
/**
* 功能描述:
*
* @Author: suge
* @Date: 2021/12/28 16:47
**/
public class SpaceTreeUtil {
private volatile static SpaceTreeUtil INSTANCE;
public SpaceTreeUtil() {
}
public static SpaceTreeUtil getInstance() {
if (INSTANCE == null) {
synchronized (SpaceTreeUtil.class) {
if (INSTANCE == null) {
INSTANCE = new SpaceTreeUtil();
}
}
}
return INSTANCE;
}
public ZhxyRsCommontReply enquireTree(List<ZhxyRsCommontReply> treeItemList) {
if (treeItemList.isEmpty()) {
return null;
}
// 过滤空对象
List<ZhxyRsCommontReply> treeItems = treeItemList.stream().filter(Objects::nonNull).collect(Collectors.toList());
// 存储 id treeItem
HashMap<Object, ZhxyRsCommontReply> itemMap = new HashMap<>();
treeItems.forEach(treeItem -> {
itemMap.put(treeItem.getCrId(), treeItem);
});
// 声明一个变量存放根节点
ZhxyRsCommontReply root = null;
// 数据组装
for (ZhxyRsCommontReply treeItem : treeItems) {
Long pid = treeItem.getCrParentid();
if (pid == 0) {
// 说明该节点为根节点
root = treeItem;
continue;
}
ZhxyRsCommontReply parent = itemMap.get(pid);
parent.getZhxyRsCommontReplies().add(treeItem);
}
return root;
}
public List<ZhxyRsCommontReply> buildDeptTree(List<ZhxyRsCommontReply> depts)
{
List<ZhxyRsCommontReply> returnList = new ArrayList<ZhxyRsCommontReply>();
List<Long> tempList = new ArrayList<Long>();
for (ZhxyRsCommontReply dept : depts)
{
tempList.add(dept.getCrId());
}
for (Iterator<ZhxyRsCommontReply> iterator = depts.iterator(); iterator.hasNext();)
{
ZhxyRsCommontReply dept = (ZhxyRsCommontReply) iterator.next();
// 如果是顶级节点, 遍历该父节点的所有子节点
if (!tempList.contains(dept.getCrParentid()))
{
recursionFn(depts, dept);
returnList.add(dept);
}
}
if (returnList.isEmpty())
{
returnList = depts;
}
return returnList;
}
private void recursionFn(List<ZhxyRsCommontReply> list, ZhxyRsCommontReply t)
{
// 得到子节点列表
List<ZhxyRsCommontReply> childList = getChildList(list, t);
t.setZhxyRsCommontReplies(childList);
for (ZhxyRsCommontReply tChild : childList)
{
if (hasChild(list, tChild))
{
recursionFn(list, tChild);
}
}
}
/**
* 得到子节点列表
*/
private List<ZhxyRsCommontReply> getChildList(List<ZhxyRsCommontReply> list, ZhxyRsCommontReply t)
{
List<ZhxyRsCommontReply> tlist = new ArrayList<ZhxyRsCommontReply>();
Iterator<ZhxyRsCommontReply> it = list.iterator();
while (it.hasNext())
{
ZhxyRsCommontReply n = (ZhxyRsCommontReply) it.next();
if (StringUtils.isNotNull(n.getCrParentid()) && n.getCrParentid().longValue() == t.getCrId().longValue())
{
tlist.add(n);
}
}
return tlist;
}
/**
* 判断是否有子节点
*/
private boolean hasChild(List<ZhxyRsCommontReply> list, ZhxyRsCommontReply t)
{
return getChildList(list, t).size() > 0;
}
}
第二种实现方法
/**
* 功能描述:
*
* @Author: suge
* @Date: 2021/12/28 16:47
**/
public class TreeUtil {
private volatile static TreeUtil INSTANCE;
public TreeUtil() {
}
public static TreeUtil getInstance() {
if (INSTANCE == null) {
synchronized (TreeUtil.class) {
if (INSTANCE == null) {
INSTANCE = new TreeUtil();
}
}
}
return INSTANCE;
}
public TreeItemVO enquireTree(List<TreeItemVO> treeItemList) {
if (treeItemList.isEmpty()) {
return null;
}
// 过滤空对象
List<TreeItemVO> treeItems = treeItemList.stream().filter(treeItem -> treeItem != null).collect(Collectors.toList());
// 存储 id treeItem
// HashMap<Object, TreeItemVO> itemMap = new HashMap<>();
// treeItems.forEach(treeItem -> {
// itemMap.put(treeItem.getDepositId(), treeItem);
// });
Map<Object, TreeItemVO> map = treeItems.stream().collect(Collectors.toMap(TreeItemVO::getDepositId, Function.identity()));
// 声明一个变量存放根节点
TreeItemVO root = null;
// 数据组装
for (TreeItemVO treeItem : treeItems) {
Integer pid = treeItem.getParentId();
if (pid == 0) {
// 说明该节点为根节点
root = treeItem;
continue;
}
TreeItemVO parent = itemMap.get(pid);
parent.getChildren().add(treeItem);
}
return root;
}
}
RabbitMQ
MQutil
package Util;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 功能描述:
*
* @Author: suge
* @Date: 2022/1/13 18:20
**/
public class MQutile {
private static ConnectionFactory connectionFactory;
static{
connectionFactory = new ConnectionFactory();
//设置连接rabbitmq主机
connectionFactory.setHost("localhost");
//设置端口
connectionFactory.setPort(5672);
//设置连接那个虚拟主机
connectionFactory.setVirtualHost("/ems");
//设置访问虚拟主机的用户名和密码
connectionFactory.setUsername("admin");
connectionFactory.setPassword("admin123");
}
public static Connection Mqutile() {
try {
return connectionFactory.newConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return null;
}
public static void closeConnectionAndChanel(Channel channel, Connection connection) {
try {
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
Provider
package helloword;
import Util.MQutile;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;
/**
* 功能描述:
*
* @Author: suge
* @Date: 2022/1/13 16:21
**/
public class Provider {
//生产消息
@Test
public void testSendMessge() throws IOException, TimeoutException {
// //建立链接mq的链接工厂对象
// ConnectionFactory connectionFactory = new ConnectionFactory();
// //设置连接rabbitmq主机
// connectionFactory.setHost("localhost");
// //设置端口
// connectionFactory.setPort(5672);
// //设置连接那个虚拟主机
// connectionFactory.setVirtualHost("/ems");
// //设置访问虚拟主机的用户名和密码
// connectionFactory.setUsername("admin");
// connectionFactory.setPassword("admin123");
// //获取连接对象
// Connection connection = connectionFactory.newConnection();
// //获取连接中通道
// Channel channel = connection.createChannel();
// //通道绑定对应的消息队列
// //参数1:队列名称 如果队列不存在自动创建
// //参数2:用来定义队列的特性,是否要持久化,true持久化队列(为trueh会把队列存在磁盘中),false不持久化(该队列会被删除)
// //参数3:是否独占队列 ture 代表独占队列,false 不独占
// //参数4:autoDelete 是否在消费完成后自动删除队列 true 自动删除 false 不自动删除
// //参数5:arguments额外附件参数
// channel.queueDeclare("hello", false, false, false, null);
Connection mqutile = MQutile.Mqutile();
Channel channel = mqutile.createChannel();
channel.queueDeclare("hello", false, false, false, null);
//发布消息
//参数1:交换机名称 参数2:队列名称 参数3:传递消息额外设置 参数4: 消息的具体消息
channel.basicPublish("", "hello", null, "hello world".getBytes());
MQutile.closeConnectionAndChanel(channel,mqutile);
}
}
Customer
package helloword;
import Util.MQutile;
import com.rabbitmq.client.*;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 功能描述:
*
* @Author: suge
* @Date: 2022/1/13 18:00
**/
public class Customer {
public static void main(String[] args) throws IOException, TimeoutException {
// //建立链接mq的链接工厂对象
// ConnectionFactory connectionFactory = new ConnectionFactory();
// //设置连接rabbitmq主机
// connectionFactory.setHost("localhost");
// //设置端口
// connectionFactory.setPort(5672);
// //设置连接那个虚拟主机
// connectionFactory.setVirtualHost("/ems");
// //设置访问虚拟主机的用户名和密码
// connectionFactory.setUsername("admin");
// connectionFactory.setPassword("admin123");
// Connection connection = connectionFactory.newConnection();
Connection mqutile = MQutile.Mqutile();
Channel channel = mqutile.createChannel();
channel.queueDeclare("hello", false, false, false, null);
//消费消息
//参数1:消费那个队列的消息 参数2:开始消息的自动确认机制 参数3:消费消息时的回调接口
channel.basicConsume("hello", true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("--------------------"+new String(body));
super.handleDelivery(consumerTag, envelope, properties, body);
}
});
}
}
Ribbon的负载均衡代码
接口第几次请求数%服务器集群总数量 = 实际调用服务器位置下标,每次服务重启动后接口计数从1开始
源码: next = (current + 1) % modulo;
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
} else {
Server server = null;
int count = 0;
while(true) {
if (server == null && count++ < 10) {
List<Server> reachableServers = lb.getReachableServers();
List<Server> allServers = lb.getAllServers();//因为eureka保证的是AP原则
,保证高可用所以是从Allservices轮询
int upCount = reachableServers.size();
int serverCount = allServers.size();
if (upCount != 0 && serverCount != 0) {
int nextServerIndex = this.incrementAndGetModulo(serverCount);
server = (Server)allServers.get(nextServerIndex);
if (server == null) {
Thread.yield();
} else {
if (server.isAlive() && server.isReadyToServe()) {
return server;
}
server = null;
}
continue;
}
log.warn("No up servers available from load balancer: " + lb);
return null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: " + lb);
}
return server;
}
}
}
--------------------------------------------------------------------------------------------
private int incrementAndGetModulo(int modulo) {
int current;
int next;
do {
current = this.nextServerCyclicCounter.get();
next = (current + 1) % modulo;
} while(!this.nextServerCyclicCounter.compareAndSet(current, next));//经典cas自旋锁
return next;
}
比较并交换: 将期望值expect与传入对象this在内存中的偏移量为valueoffset的值作比较,
如果相等, 就把update赋值给valueoffset, 返回true.
cas应用:cas有3个操作数,内存值V,旧的预期值A,要修改的更新值B.而且仅当预期值A和内存之V
相同时,将内存值V修改为B,否则什么都不做
atomic依赖的Unsafe类中的cas,Unsafe类基本都是Native方法,是一条CPU源语,天生不能被打断,
由于是操作底层所以叫做Unsafe(不安全)
mysql_start.sh
read -p '请输入你要下载的mysql地址:' url
echo '你输入的地址是 '$url
wget -i -c $url
yum -y install ${url##*/} -qa
yum -y install mysql-community-server
echo '-----启动mysql并查看状态-----'
systemctl start mysqld.service
systemctl status mysqld.service
mysql_remove.sh
echo '查看是否有预安装的mysql,如果有删除'
rpm -qa | grep -i mysql
rpm -e mysql*.noarch
nginx.sh
#!/bin/sh
echo "nginx一键安装启动"
echo '--------安装nginx环境中---------'
yum -y install pcre pcre-devel zlib zlib-devel openssl openssl-devel
echo '-------拉取nginx压缩包中------'
wget http://nginx.org/download/nginx-1.9.9.tar.gz
echo '------解压拉取的nginx安装包------'
tar -zxvf nginx-*.tar.gz
echo '------编译并安装nginx------'
cd nginx-1.9.9
./configure
make
make install
rabbitmq.sh
#安装依赖和rabbitmq
rpm -ivh erlang-22.0.7-1.el7.x86_64.rpm
rpm -ivh socat-1.7.3.2-2.el7.x86_64.rpm
rpm -ivh rabbitmq-server-3.7.18-1.el7.noarch.rpm
#这个命令是用于拷贝rabbitmq.config用的
cp /usr/share/doc/rabbitmq-server-3.7.18/rabbitmq.config.example /etc/rabbitmq/rabbitmq.config