repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/event/QrsceneSubscribeEventMessage.java
src/main/java/org/weixin4j/model/message/event/QrsceneSubscribeEventMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.event; import org.weixin4j.model.message.EventType; /** * 扫描带参数二维码事件 * * 用户未关注 * * @author yangqisheng * @since 0.0.1 */ public class QrsceneSubscribeEventMessage extends EventMessage { //事件KEY值,qrscene_为前缀,后面为二维码的参数值 private String EventKey; //二维码的ticket,可用来换取二维码图片 private String Ticket; @Override public String getEvent() { return EventType.Subscribe.toString(); } public String getEventKey() { return EventKey; } public void setEventKey(String EventKey) { this.EventKey = EventKey; } public String getTicket() { return Ticket; } public void setTicket(String Ticket) { this.Ticket = Ticket; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/event/ScanCodeWaitMsgEventMessage.java
src/main/java/org/weixin4j/model/message/event/ScanCodeWaitMsgEventMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.event; import org.weixin4j.model.message.EventType; import org.weixin4j.model.message.ScanCodeInfo; /** * 自定义菜单事件 * * 扫码推事件且弹出“消息接收中”提示框的事件推送 * * @author yangqisheng * @since 0.0.1 */ public class ScanCodeWaitMsgEventMessage extends EventMessage { //事件KEY值,与自定义菜单接口中KEY值对应 private String EventKey; //扫描信息 private ScanCodeInfo ScanCodeInfo; @Override public String getEvent() { return EventType.Scancode_Waitmsg.toString(); } public String getEventKey() { return EventKey; } public void setEventKey(String EventKey) { this.EventKey = EventKey; } public ScanCodeInfo getScanCodeInfo() { return ScanCodeInfo; } public void setScanCodeInfo(ScanCodeInfo ScanCodeInfo) { this.ScanCodeInfo = ScanCodeInfo; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/event/LocationEventMessage.java
src/main/java/org/weixin4j/model/message/event/LocationEventMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.event; import org.weixin4j.model.message.EventType; /** * 上报地理位置事件 * * @author yangqisheng * @since 0.0.1 */ public class LocationEventMessage extends EventMessage { //地理位置纬度 private String Latitude; //地理位置经度 private String Longitude; //地理位置精度 private String Precision; @Override public String getEvent() { return EventType.Location.toString(); } public String getLatitude() { return Latitude; } public void setLatitude(String Latitude) { this.Latitude = Latitude; } public String getLongitude() { return Longitude; } public void setLongitude(String Longitude) { this.Longitude = Longitude; } public String getPrecision() { return Precision; } public void setPrecision(String Precision) { this.Precision = Precision; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/event/PicSysPhotoEventMessage.java
src/main/java/org/weixin4j/model/message/event/PicSysPhotoEventMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.event; import org.weixin4j.model.message.EventType; import org.weixin4j.model.message.SendPicsInfo; /** * 自定义菜单事件 * * 扫码推事件的事件推送 * * @author yangqisheng * @since 0.0.1 */ public class PicSysPhotoEventMessage extends EventMessage { //事件KEY值,与自定义菜单接口中KEY值对应 private String EventKey; //发送的图片信息 private SendPicsInfo SendPicsInfo; @Override public String getEvent() { return EventType.Pic_Sysphoto.toString(); } public String getEventKey() { return EventKey; } public void setEventKey(String EventKey) { this.EventKey = EventKey; } public SendPicsInfo getSendPicsInfo() { return SendPicsInfo; } public void setSendPicsInfo(SendPicsInfo SendPicsInfo) { this.SendPicsInfo = SendPicsInfo; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/event/SubscribeEventMessage.java
src/main/java/org/weixin4j/model/message/event/SubscribeEventMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.event; import org.weixin4j.model.message.EventType; /** * 关注事件 * * @author yangqisheng * @since 0.0.1 */ public class SubscribeEventMessage extends EventMessage { @Override public String getEvent() { return EventType.Subscribe.toString(); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/event/PicPhotoOrAlbumEventMessage.java
src/main/java/org/weixin4j/model/message/event/PicPhotoOrAlbumEventMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.event; import org.weixin4j.model.message.EventType; import org.weixin4j.model.message.SendPicsInfo; /** * 自定义菜单事件 * * 弹出拍照或者相册发图的事件推送 * * @author yangqisheng * @since 0.0.1 */ public class PicPhotoOrAlbumEventMessage extends EventMessage { //事件KEY值,与自定义菜单接口中KEY值对应 private String EventKey; //发送的图片信息 private SendPicsInfo SendPicsInfo; @Override public String getEvent() { return EventType.Pic_Photo_OR_Album.toString(); } public String getEventKey() { return EventKey; } public void setEventKey(String EventKey) { this.EventKey = EventKey; } public SendPicsInfo getSendPicsInfo() { return SendPicsInfo; } public void setSendPicsInfo(SendPicsInfo SendPicsInfo) { this.SendPicsInfo = SendPicsInfo; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/event/ViewEventMessage.java
src/main/java/org/weixin4j/model/message/event/ViewEventMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.event; import org.weixin4j.model.message.EventType; /** * 自定义菜单事件 * * 点击菜单跳转链接时的事件推送 * * @author yangqisheng * @since 0.0.1 */ public class ViewEventMessage extends EventMessage { //事件KEY值,设置的跳转URL private String EventKey; private String MenuId; @Override public String getEvent() { return EventType.View.toString(); } public String getEventKey() { return EventKey; } public void setEventKey(String EventKey) { this.EventKey = EventKey; } public String getMenuId() { return MenuId; } public void setMenuId(String MenuId) { this.MenuId = MenuId; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/event/ClickEventMessage.java
src/main/java/org/weixin4j/model/message/event/ClickEventMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.event; import org.weixin4j.model.message.EventType; /** * 自定义菜单事件 * * 点击菜单拉取消息时的事件推送 * * @author yangqisheng * @since 0.0.1 */ public class ClickEventMessage extends EventMessage { //事件KEY值,与自定义菜单接口中KEY值对应 private String EventKey; @Override public String getEvent() { return EventType.Click.toString(); } public String getEventKey() { return EventKey; } public void setEventKey(String EventKey) { this.EventKey = EventKey; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/template/Miniprogram.java
src/main/java/org/weixin4j/model/message/template/Miniprogram.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.template; /** * 实体类对象,用来设置<tt>TemplateMessage</tt>中的跳小程序所需数据 * * @author yangqisheng * @since 0.1.0 */ public class Miniprogram implements java.io.Serializable { /** * 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系) */ private String appid; /** * 所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar) */ private String pagepath; public Miniprogram() { } public Miniprogram(String appid, String pagepath) { this.appid = appid; this.pagepath = pagepath; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getPagepath() { return pagepath; } public void setPagepath(String pagepath) { this.pagepath = pagepath; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/template/TemplateMessage.java
src/main/java/org/weixin4j/model/message/template/TemplateMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.template; import java.util.List; /** * 实体类对象,发送模板消息对象 * * @author yangqisheng * @since 0.1.0 */ public class TemplateMessage implements java.io.Serializable { /** * 接收者openid,对应官方参数touser */ private String openid; /** * 模板ID */ private String templateId; /** * 模板跳转链接 */ private String url; /** * 跳小程序所需数据,不需跳小程序可不用传该数据 */ private Miniprogram miniprogram; /** * 模板数据 */ private List<TemplateData> data; public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Miniprogram getMiniprogram() { return miniprogram; } public void setMiniprogram(Miniprogram miniprogram) { this.miniprogram = miniprogram; } public List<TemplateData> getData() { return data; } public void setData(List<TemplateData> data) { this.data = data; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/template/TemplateData.java
src/main/java/org/weixin4j/model/message/template/TemplateData.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.template; /** * 实体类对象,用来设置<tt>TemplateMessage</tt>中的模板数据 * * @author yangqisheng * @since 0.1.0 */ public class TemplateData implements java.io.Serializable { /** * 字段Key */ private String key; /** * 值 */ private String value; /** * 颜色 */ private String color; public TemplateData() { } public TemplateData(String key, String value) { this.key = key; this.value = value; } public TemplateData(String key, String value, String color) { this.key = key; this.value = value; this.color = color; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/output/VideoOutputMessage.java
src/main/java/org/weixin4j/model/message/output/VideoOutputMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.output; import org.weixin4j.model.message.Video; import org.weixin4j.model.message.OutputMessage; /** * 这个类实现了<tt>OutputMessage</tt>,用来回复视频消息 * * <p> * 提供了获取视频Id<code>getMediaId()</code>等主要方法.</p> * * @author yangqisheng * @since 0.0.1 */ public class VideoOutputMessage extends OutputMessage { /** * 消息类型:视频消息 */ private final String MsgType = "video"; /** * 通过上传多媒体文件,得到的id */ private Video Video; /** * 创建一个视频 Output Message. * * 并且MsgType的值为video. */ public VideoOutputMessage() { } /** * 创建一个视频 Output Message. * * 并且MsgType的值为video. * * @param video 视频 */ public VideoOutputMessage(Video video) { Video = video; } /** * 获取 消息类型 * * @return 消息类型 */ @Override public String getMsgType() { return MsgType; } /** * 获取 通过上传多媒体文件,得到的id * * @return 通过上传多媒体文件,得到的id */ public Video getVideo() { return Video; } /** * 设置 通过上传多媒体文件,得到的id * * @param video 通过上传多媒体文件,得到的id */ public void setVideo(Video video) { Video = video; } @Override public String toXML() { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(this.getToUserName()).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(this.getFromUserName()).append("]]></FromUserName>"); sb.append("<CreateTime>").append(this.getCreateTime()).append("</CreateTime>"); sb.append("<MsgType><![CDATA[" + this.MsgType + "]]></MsgType>"); sb.append("<Video>"); sb.append("<MediaId><![CDATA[").append(this.getVideo().getMediaId()).append("]]></MediaId>"); sb.append("<Title><![CDATA[").append(this.getVideo().getTitle()).append("]]></Title>"); sb.append("<Description><![CDATA[").append(this.getVideo().getDescription()).append("]]></Description>"); sb.append("</Video>"); sb.append("</xml>"); return sb.toString(); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/output/VoiceOutputMessage.java
src/main/java/org/weixin4j/model/message/output/VoiceOutputMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.output; import org.weixin4j.model.message.Voice; import org.weixin4j.model.message.OutputMessage; /** * 这个类实现了<tt>OutputMessage</tt>,用来回复语音消息 * * <p>提供了获取语音Id<code>getVoice()</code>等主要方法.</p> * * @author yangqisheng * @since 0.0.1 */ public class VoiceOutputMessage extends OutputMessage { /** * 消息类型:语音消息 */ private final String MsgType = "voice"; /** * 通过上传多媒体文件,得到的id封装的Voice对象 */ private Voice Voice; /** * 创建一个新的 Output Message.并且MsgType的值为voice. */ public VoiceOutputMessage() { } /** * 创建一个自定义语音Id mediaId的Output Message. * * @param voice 语音资源Id */ public VoiceOutputMessage(Voice voice) { Voice = voice; } /** * 获取 消息类型 * * @return 消息类型 */ @Override public String getMsgType() { return MsgType; } /** * 获取 通过上传多媒体文件,得到的id封装的Voice对象 * * @return 通过上传多媒体文件,得到的id封装的Voice对象 */ public Voice getVoice() { return Voice; } /** * 设置 通过上传多媒体文件,得到的id封装的Voice对象 * * @param voice 通过上传多媒体文件,得到的id封装的Voice对象 */ public void setVoice(Voice voice) { Voice = voice; } @Override public String toXML() { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(this.getToUserName()).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(this.getFromUserName()).append("]]></FromUserName>"); sb.append("<CreateTime>").append(this.getCreateTime()).append("</CreateTime>"); sb.append("<MsgType><![CDATA[" + this.MsgType + "]]></MsgType>"); sb.append("<Voice>"); sb.append("<MediaId><![CDATA[").append(this.getVoice().getMediaId()).append("]]></MediaId>"); sb.append("</Voice>"); sb.append("</xml>"); return sb.toString(); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/output/NewsOutputMessage.java
src/main/java/org/weixin4j/model/message/output/NewsOutputMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.output; import org.weixin4j.model.message.Articles; import org.weixin4j.model.message.OutputMessage; import java.util.ArrayList; import java.util.List; /** * 这个类实现了<tt>OutputMessage</tt>,用来回复图文消息 * * <p> * 提供了获取多条图文消息信息<code>getArticles()</code>等主要方法.</p> * * @author yangqisheng * @since 0.0.1 */ public class NewsOutputMessage extends OutputMessage { /** * 消息类型:图文消息 */ private final String MsgType = "news"; /** * 图文消息个数,限制为10条以内 */ private Integer ArticleCount; /** * 多条图文消息信息,默认第一个item为大图,注意,如果图文数超过10,则将会无响应 */ private List<Articles> Articles; /** * 获取 消息类型 * * @return 消息类型 */ @Override public String getMsgType() { return MsgType; } /** * 获取 图文消息个数 * * @return 图文消息个数 */ public Integer getArticleCount() { return ArticleCount; } /** * 获取 多条图文消息信息 * * @return 多条图文消息信息,默认第一个item为大图,注意,如果图文数超过10,则只读取前10个 */ public List<Articles> getArticles() { return Articles; } /** * 设置 多条图文消息信息 * * @param articles 多条图文消息信息,默认第一个item为大图,注意,如果图文数超过10,则只读取前10个 */ public void setArticles(List<Articles> articles) { if (articles != null) { if (articles.size() > 10) { articles = new ArrayList<Articles>(articles.subList(0, 10)); } ArticleCount = articles.size(); } Articles = articles; } @Override public String toXML() { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(this.getToUserName()).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(this.getFromUserName()).append("]]></FromUserName>"); sb.append("<CreateTime>").append(this.getCreateTime()).append("</CreateTime>"); sb.append("<MsgType><![CDATA[" + this.MsgType + "]]></MsgType>"); sb.append("<ArticleCount>").append(this.ArticleCount).append("</ArticleCount>"); sb.append("<Articles>"); for (Articles article : Articles) { sb.append("<item>"); sb.append("<Title><![CDATA[").append(article.getTitle()).append("]]></Title>"); sb.append("<Description><![CDATA[").append(article.getDescription()).append("]]></Description>"); sb.append("<PicUrl><![CDATA[").append(article.getPicUrl()).append("]]></PicUrl>"); sb.append("<Url><![CDATA[").append(article.getUrl()).append("]]></Url>"); sb.append("</item>"); } sb.append("</Articles>"); sb.append("</xml>"); return sb.toString(); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/output/MusicOutputMessage.java
src/main/java/org/weixin4j/model/message/output/MusicOutputMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.output; import org.weixin4j.model.message.Music; import org.weixin4j.model.message.OutputMessage; /** * 这个类实现了<tt>OutputMessage</tt>,用来回复音乐消息 * * <p> * 提供了获取音乐链接<code>getMusicURL()</code>等主要方法.</p> * * @author yangqisheng * @since 0.0.1 */ public class MusicOutputMessage extends OutputMessage { /** * 消息类型:音乐消息 */ private final String MsgType = "music"; /** * 音乐消息对象 */ private Music Music; @Override public String getMsgType() { return MsgType; } public MusicOutputMessage(Music music) { super(); Music = music; } public Music getMusic() { return Music; } public void setMusic(Music Music) { this.Music = Music; } @Override public String toXML() { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(this.getToUserName()).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(this.getFromUserName()).append("]]></FromUserName>"); sb.append("<CreateTime>").append(this.getCreateTime()).append("</CreateTime>"); sb.append("<MsgType><![CDATA[" + this.MsgType + "]]></MsgType>"); sb.append("<Music>"); sb.append("<Title><![CDATA[").append(this.getMusic().getTitle()).append("]]></Title>"); sb.append("<Description><![CDATA[").append(this.getMusic().getDescription()).append("]]></Description>"); sb.append("<MusicUrl><![CDATA[").append(this.getMusic().getMusicUrl()).append("]]></MusicUrl>"); sb.append("<HQMusicUrl><![CDATA[").append(this.getMusic().getHQMusicUrl()).append("]]></HQMusicUrl>"); sb.append("<ThumbMediaId><![CDATA[").append(this.getMusic().getThumbMediaId()).append("]]></ThumbMediaId>"); sb.append("</Music>"); sb.append("</xml>"); return sb.toString(); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/output/ImageOutputMessage.java
src/main/java/org/weixin4j/model/message/output/ImageOutputMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.output; import org.weixin4j.model.message.Image; import org.weixin4j.model.message.OutputMessage; /** * 这个类实现了<tt>OutputMessage</tt>,用来回复图片消息 * * <p> * 提供了获取图片Id<code>getMediaId()</code>等主要方法.</p> * * @author yangqisheng * @since 0.0.1 */ public class ImageOutputMessage extends OutputMessage { /** * 消息类型:图片消息 */ private final String MsgType = "image"; /** * 通过上传多媒体文件,得到的id */ private Image Image; /** * 创建一个图片 Output Message. * * 并且MsgType的值为image. */ public ImageOutputMessage() { } /** * 创建一个图片 的Output Message. * * 并且MsgType的值为image. * * @param image 图片 */ public ImageOutputMessage(Image image) { this.Image = image; } /** * 获取 消息类型 * * @return 消息类型 */ @Override public String getMsgType() { return MsgType; } /** * 获取 通过上传多媒体文件,得到的id * * @return 通过上传多媒体文件,得到的id封装的image对象 */ public Image getImage() { return this.Image; } /** * 设置 通过上传多媒体文件,得到的id * * @param image 通过上传多媒体文件,得到的id封装的image对象 */ public void setImage(Image image) { this.Image = image; } @Override public String toXML() { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(this.getToUserName()).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(this.getFromUserName()).append("]]></FromUserName>"); sb.append("<CreateTime>").append(this.getCreateTime()).append("</CreateTime>"); sb.append("<MsgType><![CDATA[" + this.MsgType + "]]></MsgType>"); sb.append("<Image>"); sb.append("<MediaId><![CDATA[").append(this.getImage().getMediaId()).append("]]></MediaId>"); sb.append("</Image>"); sb.append("</xml>"); return sb.toString(); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/message/output/TextOutputMessage.java
src/main/java/org/weixin4j/model/message/output/TextOutputMessage.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.message.output; import org.weixin4j.model.message.OutputMessage; /** * 这个类实现了<tt>OutputMessage</tt>,用来回复文本消息 * * <p> * 提供了获取文本内容<code>getContent()</code>等主要方法.</p> * * @author yangqisheng * @since 0.0.1 */ public class TextOutputMessage extends OutputMessage { /** * 消息类型:文本消息 */ private final String MsgType = "text"; /** * 文本消息 */ private String Content; /** * 创建一个新的 Output Message.并且MsgType的值为text. */ public TextOutputMessage() { } /** * 创建一个自定义文本内容content的Output Message. * * @param content 文本内容 */ public TextOutputMessage(String content) { Content = content; } /** * 获取 消息类型 * * @return 消息类型 */ @Override public String getMsgType() { return MsgType; } /** * 获取 文本消息 * * @return 文本消息 */ public String getContent() { return Content; } /** * 设置 文本消息 * * @param content 文本消息 */ public void setContent(String content) { Content = content; } @Override public String toXML() { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(this.getToUserName()).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(this.getFromUserName()).append("]]></FromUserName>"); sb.append("<CreateTime>").append(this.getCreateTime()).append("</CreateTime>"); sb.append("<MsgType><![CDATA[" + this.MsgType + "]]></MsgType>"); sb.append("<Content><![CDATA[").append(this.getContent()).append("]]></Content>"); sb.append("</xml>"); return sb.toString(); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/media/Article.java
src/main/java/org/weixin4j/model/media/Article.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.media; /** * 图文消息对象 * * @author yangqisheng * @since 0.0.1 */ public class Article { private String thumb_media_id; //图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得 private String author; //图文消息的作者 private String title; //图文消息的标题 private String content_source_url; //在图文消息页面点击“阅读原文”后的页面 private String content; //图文消息页面的内容,支持HTML标签 private String digest; //图文消息的描述,如本字段为空,则默认抓取正文前64个字 private int show_cover_pic;//是否显示封面,1为显示,0为不显示 /** * @return the thumb_media_id */ public String getThumb_media_id() { return thumb_media_id; } /** * @param thumb_media_id the thumb_media_id to set */ public void setThumb_media_id(String thumb_media_id) { this.thumb_media_id = thumb_media_id; } /** * @return the author */ public String getAuthor() { return author; } /** * @param author the author to set */ public void setAuthor(String author) { this.author = author; } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the content_source_url */ public String getContent_source_url() { return content_source_url; } /** * @param content_source_url the content_source_url to set */ public void setContent_source_url(String content_source_url) { this.content_source_url = content_source_url; } /** * @return the content */ public String getContent() { return content; } /** * @param content the content to set */ public void setContent(String content) { this.content = content; } /** * @return the digest */ public String getDigest() { return digest; } /** * @param digest the digest to set */ public void setDigest(String digest) { this.digest = digest; } /** * @return the show_cover_pic */ public int getShow_cover_pic() { return show_cover_pic; } /** * @param show_cover_pic the show_cover_pic to set */ public void setShow_cover_pic(int show_cover_pic) { this.show_cover_pic = show_cover_pic; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/media/Attachment.java
src/main/java/org/weixin4j/model/media/Attachment.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.media; import java.io.BufferedInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * 附件 * * @author yangqisheng * @since 0.0.1 */ public class Attachment { private String fileName; private String fullName; private String suffix; private String contentLength; private String contentType; private BufferedInputStream fileStream; private String error; /** * 附件名称 * * @return 附件名称 */ public String getFileName() { return fileName; } /** * 设置 附件名称 * * @param fileName 附件名称 */ public void setFileName(String fileName) { this.fileName = fileName; } /** * 附件全名 * * @return 附件全名 */ public String getFullName() { return fullName; } /** * 设置附件全名 * * @param fullName 附件全名 */ public void setFullName(String fullName) { this.fullName = fullName; } /** * 附件后缀 * * @return 附件后缀 */ public String getSuffix() { return suffix; } /** * 设置 附件后缀 * * @param suffix 附件后缀 */ public void setSuffix(String suffix) { this.suffix = suffix; } /** * 内容长度 * * @return 内容长度 */ public String getContentLength() { return contentLength; } /** * 设置内容长度 * * @param contentLength 内容长度 */ public void setContentLength(String contentLength) { this.contentLength = contentLength; } /** * 文件类型 * * @return 文件类型 */ public String getContentType() { return contentType; } /** * 设置 文件类型 * * @param contentType 文件类型 */ public void setContentType(String contentType) { this.contentType = contentType; } /** * 文件输入流 * * @return 文件输入流 */ public BufferedInputStream getFileStream() { return fileStream; } /** * 设置 文件输入流 * * @param fileStream 文件输入流 */ public void setFileStream(BufferedInputStream fileStream) { this.fileStream = fileStream; } /** * 保存为图片 * * @param filePath 文件路径 * @param fileName 文件名称 * @return 文件对象 * @throws java.io.FileNotFoundException */ public File saveToImageFile(String filePath, String fileName) throws FileNotFoundException, IOException { String defaultSubffix = ".jpg"; if (fileName.contains(".")) { defaultSubffix = fileName.substring(fileName.lastIndexOf(".")); fileName = fileName.substring(0, fileName.lastIndexOf(".")); } return saveToFile(filePath, fileName, defaultSubffix); } /** * 保存到文件 * * @param filePath 文件路径 * @param fileName 文件名称(不包含后缀) * @param defaultSubffix 默认文件后缀 * @return 文件对象 * @throws java.io.FileNotFoundException */ public File saveToFile(String filePath, String fileName, String defaultSubffix) throws FileNotFoundException, IOException { if (this.error == null) { //默认格式 String subffix = defaultSubffix; //校验文件格式 if (contentType.startsWith("image")) { //图片文件 if (contentType.equals("image/jpeg")) { subffix = "jpg"; } else if (contentType.equals("image/jpeg")) { subffix = "png"; } else if (contentType.equals("image/gif")) { subffix = "gif"; } else { subffix = "jpg"; } } else if (contentType.startsWith("voice") || contentType.startsWith("audio")) { //音频文件 if (contentType.equals("voice/mp3") || contentType.equals("audio/mp3")) { subffix = "mp3"; } else if (contentType.equals("voice/amr") || contentType.equals("audio/amr")) { subffix = "amr"; } else if (contentType.equals("voice/speex")) { subffix = "speex"; } else { subffix = "mp3"; } } else if (contentType.startsWith("video")) { //视频文件 subffix = "mp4"; } filePath = filePath.replace("/", File.separator); filePath = filePath.endsWith(File.separator) ? filePath : filePath + File.separator; File directory = new File(filePath); if (!directory.exists()) { directory.mkdirs(); } File file = new File(filePath + fileName + (subffix.indexOf(".") == 0 ? subffix : "." + subffix)); FileOutputStream out = new FileOutputStream(file); byte[] bs = new byte[1024]; int len; while ((len = fileStream.read(bs)) != -1) { out.write(bs, 0, len); } return file; } return null; } /** * 错误消息 * * @return 错误消息 */ public String getError() { return error; } /** * 设置 错误消息 * * @param error 错误消息 */ public void setError(String error) { this.error = error; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/PicWeixinButton.java
src/main/java/org/weixin4j/model/menu/PicWeixinButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 微信相册发图 * * @author yangqisheng * @since 0.0.1 */ public class PicWeixinButton extends SingleButton { /** * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节 */ private String key; public PicWeixinButton(String name, String key) { super(name); this.key = key; } public String getType() { return ButtonType.Pic_Weixin.toString(); } /** * 获取 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @return 菜单KEY值 */ public String getKey() { return key; } /** * 设置 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @param key 菜单KEY值 */ public void setKey(String key) { this.key = key; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/LocationSelectButton.java
src/main/java/org/weixin4j/model/menu/LocationSelectButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 发送地理位置 * * @author yangqisheng * @since 0.0.1 */ public class LocationSelectButton extends SingleButton { /** * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节 */ private String key; public LocationSelectButton(String name, String key) { super(name); this.key = key; } public String getType() { return ButtonType.Location_Select.toString(); } /** * 获取 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @return 菜单KEY值 */ public String getKey() { return key; } /** * 设置 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @param key 菜单KEY值 */ public void setKey(String key) { this.key = key; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/PicPhotoOrAlbumButton.java
src/main/java/org/weixin4j/model/menu/PicPhotoOrAlbumButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 拍照或者相册发图 * * @author yangqisheng * @since 0.0.1 */ public class PicPhotoOrAlbumButton extends SingleButton { /** * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节 */ private String key; public PicPhotoOrAlbumButton(String name, String key) { super(name); this.key = key; } public String getType() { return ButtonType.Pic_Photo_OR_Album.toString(); } /** * 获取 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @return 菜单KEY值 */ public String getKey() { return key; } /** * 设置 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @param key 菜单KEY值 */ public void setKey(String key) { this.key = key; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/PicSysPhotoButton.java
src/main/java/org/weixin4j/model/menu/PicSysPhotoButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 系统拍照发图 * * @author yangqisheng * @since 0.0.1 */ public class PicSysPhotoButton extends SingleButton { /** * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节 */ private String key; public PicSysPhotoButton(String name, String key) { super(name); this.key = key; } public String getType() { return ButtonType.Pic_SysPhoto.toString(); } /** * 获取 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @return 菜单KEY值 */ public String getKey() { return key; } /** * 设置 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @param key 菜单KEY值 */ public void setKey(String key) { this.key = key; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/ScancodePushButton.java
src/main/java/org/weixin4j/model/menu/ScancodePushButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 扫码推事件 * * @author yangqisheng * @since 0.0.1 */ public class ScancodePushButton extends SingleButton { /** * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节 */ private String key; public ScancodePushButton(String name, String key) { super(name); this.key = key; } public String getType() { return ButtonType.Scancode_Push.toString(); } /** * 获取 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @return 菜单KEY值 */ public String getKey() { return key; } /** * 设置 菜单KEY值 * * <p> * click类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @param key 菜单KEY值 */ public void setKey(String key) { this.key = key; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/MediaIdButton.java
src/main/java/org/weixin4j/model/menu/MediaIdButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 永久素材(图片、音频、视频、图文消息) * * @author yangqisheng * @since 0.0.1 */ public class MediaIdButton extends SingleButton { /** * 类型必须.网页链接,用户点击菜单可打开链接,不超过256字节 */ private String mediaId; public MediaIdButton(String name, String mediaId) { super(name); this.mediaId = mediaId; } public String getType() { return ButtonType.Media_Id.toString(); } /** * 获取 调用新增永久素材接口返回的合法media_id * * @return 调用新增永久素材接口返回的合法media_id */ public String getMedia_Id() { return mediaId; } /** * 设置 调用新增永久素材接口返回的合法media_id * * @param mediaId 调用新增永久素材接口返回的合法media_id */ public void setMedia_Id(String mediaId) { this.mediaId = mediaId; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/ViewButton.java
src/main/java/org/weixin4j/model/menu/ViewButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 跳转URL * * @author yangqisheng * @since 0.0.1 */ public class ViewButton extends SingleButton { /** * view类型必须.网页链接,用户点击菜单可打开链接,不超过256字节 */ private String url; public ViewButton(String name) { super(name); } public ViewButton(String name, String url) { super(name); this.url = url; } public String getType() { return ButtonType.View.toString(); } /** * 获取 网页链接 * * <p> * view类型必须.网页链接,用户点击菜单可打开链接,不超过256字节 * </p> * * @return 网页链接 */ public String getUrl() { return url; } /** * 设置 网页链接 * * <p> * view类型必须.网页链接,用户点击菜单可打开链接,不超过256字节 * </p> * * @param url 网页链接 */ public void setUrl(String url) { this.url = url; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/MiniprogramButton.java
src/main/java/org/weixin4j/model/menu/MiniprogramButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 打开小程序 * * @author yangqisheng * @since 0.1.2 */ public class MiniprogramButton extends SingleButton { /** * 小程序的appid(仅认证公众号可配置) */ private String appid; /** * 小程序的页面路径 */ private String pagepath; /** * 网页 链接,用户点击菜单可打开链接,不超过1024字节。 * * 不支持小程序的老版本客户端将打开本url。 */ private String url; public MiniprogramButton(String name) { super(name); } public MiniprogramButton(String name, String appid, String pagepath, String url) { super(name); this.appid = appid; this.pagepath = pagepath; this.url = url; } public String getType() { return ButtonType.Miniprogram.toString(); } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getPagepath() { return pagepath; } public void setPagepath(String pagepath) { this.pagepath = pagepath; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/ScancodeWaitMsgButton.java
src/main/java/org/weixin4j/model/menu/ScancodeWaitMsgButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 扫码带提示 * * @author yangqisheng * @since 0.0.1 */ public class ScancodeWaitMsgButton extends SingleButton { /** * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节 */ private String key; public ScancodeWaitMsgButton(String name, String key) { super(name); this.key = key; } public String getType() { return ButtonType.Scancode_Waitmsg.toString(); } /** * 获取 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @return 菜单KEY值 */ public String getKey() { return key; } /** * 设置 菜单KEY值 * * <p> * 类型必须.菜单KEY值,用于消息接口推送,不超过128字节</p> * * @param key 菜单KEY值 */ public void setKey(String key) { this.key = key; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/Menu.java
src/main/java/org/weixin4j/model/menu/Menu.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; /** * 菜单对象 * * @author yangqisheng * @since 0.0.1 */ public class Menu { private List<SingleButton> button; public Menu() { } public Menu(JSONObject jsonObj) { //初始化一级自定义菜单 button = new ArrayList<SingleButton>(); //获取menu对象 JSONObject menuObj = jsonObj.getJSONObject("menu"); if (menuObj != null) { //获取button列表 JSONArray buttonJson = menuObj.getJSONArray("button"); for (int i = 0; i < buttonJson.size(); i++) { JSONObject jsonButton = buttonJson.getJSONObject(i); recursion(jsonButton, null); } } } private void recursion(JSONObject jsonButton, SingleButton menuButton) { String type = null; if (jsonButton.containsKey("type")) { type = jsonButton.getString("type"); } SingleButton singleButton = null; //判断对象type if (type == null) { //有子的自定义菜单 singleButton = new SingleButton(jsonButton.getString("name")); } else if (type.equals(ButtonType.Click.toString())) { //转成点击按钮 singleButton = new ClickButton(jsonButton.getString("name"), jsonButton.getString("key")); } else if (type.equals(ButtonType.View.toString())) { //转成view按钮 singleButton = new ViewButton(jsonButton.getString("name"), jsonButton.getString("url")); } else if (type.equals(ButtonType.Scancode_Push.toString())) { //扫码推事件 singleButton = new ScancodePushButton(jsonButton.getString("name"), jsonButton.getString("key")); } else if (type.equals(ButtonType.Scancode_Waitmsg.toString())) { //扫码推事件且弹出“消息接收中”提示框 singleButton = new ScancodeWaitMsgButton(jsonButton.getString("name"), jsonButton.getString("key")); } else if (type.equals(ButtonType.Pic_SysPhoto.toString())) { //弹出系统拍照发图 singleButton = new PicSysPhotoButton(jsonButton.getString("name"), jsonButton.getString("key")); } else if (type.equals(ButtonType.Pic_Photo_OR_Album.toString())) { //弹出拍照或者相册发图 singleButton = new PicPhotoOrAlbumButton(jsonButton.getString("name"), jsonButton.getString("key")); } else if (type.equals(ButtonType.Pic_Weixin.toString())) { //弹出微信相册发图器 singleButton = new PicWeixinButton(jsonButton.getString("name"), jsonButton.getString("key")); } else if (type.equals(ButtonType.Location_Select.toString())) { //弹出地理位置选择器 singleButton = new LocationSelectButton(jsonButton.getString("name"), jsonButton.getString("key")); } else if (type.equals(ButtonType.Media_Id.toString())) { //永久素材(图片、音频、视频、图文消息) singleButton = new MediaIdButton(jsonButton.getString("name"), jsonButton.getString("media_id")); } else if (type.equals(ButtonType.View_Limited.toString())) { //永久素材(图文消息) singleButton = new ViewLimitedButton(jsonButton.getString("name"), jsonButton.getString("media_id")); } else if (type.equals(ButtonType.Miniprogram.toString())) { //小程序菜单 singleButton = new MiniprogramButton(jsonButton.getString("name"), jsonButton.getString("appid"), jsonButton.getString("pagepath"), jsonButton.getString("url")); } if (jsonButton.containsKey("sub_button")) { JSONArray sub_button = jsonButton.getJSONArray("sub_button"); //判断是否存在子菜单 if (!sub_button.isEmpty()) { //如果不为空,则添加到singleButton中 for (int i = 0; i < sub_button.size(); i++) { JSONObject jsonSubButton = sub_button.getJSONObject(i); recursion(jsonSubButton, singleButton); } } } //判断是否存在子菜单 if (menuButton == null) { //只添加一级菜单到集合中 button.add(singleButton); } else { //添加到二级自定义菜单中 menuButton.getSubButton().add(singleButton); } } /** * 转成JSON提交对象 * * @return JSON提交对象 */ public JSONObject toJSONObject() { JSONObject buttonJson = new JSONObject(); JSONArray buttonArray = new JSONArray(); if (this.button != null) { //添加一级菜单 for (SingleButton btn : button) { List<SingleButton> subButton = btn.getSubButton(); //设置顶级菜单信息 JSONObject btnJson = new JSONObject(); btnJson.put("name", btn.getName()); if (btn instanceof ViewButton) { ViewButton cBtn = (ViewButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("url", cBtn.getUrl()); } else if (btn instanceof ClickButton) { ClickButton cBtn = (ClickButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("key", cBtn.getKey()); } else if (btn instanceof ScancodePushButton) { ScancodePushButton cBtn = (ScancodePushButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("key", cBtn.getKey()); } else if (btn instanceof ScancodeWaitMsgButton) { ScancodeWaitMsgButton cBtn = (ScancodeWaitMsgButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("key", cBtn.getKey()); } else if (btn instanceof PicSysPhotoButton) { PicSysPhotoButton cBtn = (PicSysPhotoButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("key", cBtn.getKey()); } else if (btn instanceof PicPhotoOrAlbumButton) { PicPhotoOrAlbumButton cBtn = (PicPhotoOrAlbumButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("key", cBtn.getKey()); } else if (btn instanceof PicWeixinButton) { PicWeixinButton cBtn = (PicWeixinButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("key", cBtn.getKey()); } else if (btn instanceof LocationSelectButton) { LocationSelectButton cBtn = (LocationSelectButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("key", cBtn.getKey()); } else if (btn instanceof MediaIdButton) { MediaIdButton cBtn = (MediaIdButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("media_id", cBtn.getMedia_Id()); } else if (btn instanceof ViewLimitedButton) { ViewLimitedButton cBtn = (ViewLimitedButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("media_id", cBtn.getMedia_Id()); } else if (btn instanceof MiniprogramButton) { MiniprogramButton cBtn = (MiniprogramButton) btn; btnJson.put("type", cBtn.getType()); btnJson.put("url", cBtn.getUrl()); btnJson.put("appid", cBtn.getAppid()); btnJson.put("pagepath", cBtn.getPagepath()); } //设置子菜单信息 JSONArray subButtonArray = new JSONArray(); for (SingleButton subBtn : subButton) { JSONObject subBtnJson = new JSONObject(); subBtnJson.put("name", subBtn.getName()); if (subBtn instanceof ViewButton) { ViewButton cBtn = (ViewButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("url", cBtn.getUrl()); } else if (subBtn instanceof ClickButton) { ClickButton cBtn = (ClickButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("key", cBtn.getKey()); } else if (subBtn instanceof ScancodePushButton) { ScancodePushButton cBtn = (ScancodePushButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("key", cBtn.getKey()); } else if (subBtn instanceof ScancodeWaitMsgButton) { ScancodeWaitMsgButton cBtn = (ScancodeWaitMsgButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("key", cBtn.getKey()); } else if (subBtn instanceof PicSysPhotoButton) { PicSysPhotoButton cBtn = (PicSysPhotoButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("key", cBtn.getKey()); } else if (subBtn instanceof PicPhotoOrAlbumButton) { PicPhotoOrAlbumButton cBtn = (PicPhotoOrAlbumButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("key", cBtn.getKey()); } else if (subBtn instanceof PicWeixinButton) { PicWeixinButton cBtn = (PicWeixinButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("key", cBtn.getKey()); } else if (subBtn instanceof LocationSelectButton) { LocationSelectButton cBtn = (LocationSelectButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("key", cBtn.getKey()); } else if (subBtn instanceof MediaIdButton) { MediaIdButton cBtn = (MediaIdButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("media_id", cBtn.getMedia_Id()); } else if (subBtn instanceof ViewLimitedButton) { ViewLimitedButton cBtn = (ViewLimitedButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("media_id", cBtn.getMedia_Id()); } else if (subBtn instanceof MiniprogramButton) { MiniprogramButton cBtn = (MiniprogramButton) subBtn; subBtnJson.put("type", cBtn.getType()); subBtnJson.put("url", cBtn.getUrl()); subBtnJson.put("appid", cBtn.getAppid()); subBtnJson.put("pagepath", cBtn.getPagepath()); } subButtonArray.add(subBtnJson); } btnJson.put("sub_button", subButtonArray); buttonArray.add(btnJson); } } buttonJson.put("button", buttonArray); //返回创建JSON BODY return buttonJson; } public List<SingleButton> getButton() { if (button == null) { button = new ArrayList<SingleButton>(0); } return button; } public void setButton(List<SingleButton> button) { this.button = button; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/BaseButton.java
src/main/java/org/weixin4j/model/menu/BaseButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 自定义菜单按钮 * * @author yangqisheng * @since 0.0.1 */ public class BaseButton { /** * 菜单标题,不超过16个字节,子菜单不超过40个字节 */ private final String name; /** * 基础按钮 * * @param name 菜单标题 */ public BaseButton(String name) { this.name = name; } /** * 获取 菜单标题 * * @return 菜单标题 */ public String getName() { return name; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/ClickButton.java
src/main/java/org/weixin4j/model/menu/ClickButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 点击推事件 * * @author yangqisheng * @since 0.0.1 */ public class ClickButton extends SingleButton { /** * click类型必须.菜单KEY值,用于消息接口推送,不超过128字节 */ private String key; public ClickButton(String name, String key) { super(name); this.key = key; } public String getType() { return ButtonType.Click.toString(); } /** * 获取 菜单KEY值 * * <p> * click类型必须.菜单KEY值, 用于消息接口推送,不超过128字节 * </p> * * @return 菜单KEY值 */ public String getKey() { return key; } /** * 设置 菜单KEY值 * * <p> * click类型必须.菜单KEY值,用于消息接口推送,不超过128字节 * </p> * * @param key 菜单KEY值 */ public void setKey(String key) { this.key = key; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/ViewLimitedButton.java
src/main/java/org/weixin4j/model/menu/ViewLimitedButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 永久素材(只能是图文消息) * * @author yangqisheng * @since 0.0.1 */ public class ViewLimitedButton extends SingleButton { /** * 类型必须.网页链接,用户点击菜单可打开链接,不超过256字节 */ private String mediaId; public ViewLimitedButton(String name, String mediaId) { super(name); this.mediaId = mediaId; } public String getType() { return ButtonType.View_Limited.toString(); } /** * 获取 调用新增永久素材接口返回的合法media_id * * @return 调用新增永久素材接口返回的合法media_id */ public String getMedia_Id() { return mediaId; } /** * 设置 调用新增永久素材接口返回的合法media_id * * @param mediaId 调用新增永久素材接口返回的合法media_id */ public void setMedia_Id(String mediaId) { this.mediaId = mediaId; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/ButtonType.java
src/main/java/org/weixin4j/model/menu/ButtonType.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; /** * 自定义菜单类型 * * @author yangqisheng * @since 0.0.1 */ public enum ButtonType { /** * 点击推事件 */ Click("click"), /** * 跳转URL */ View("view"), /** * 扫码推事件 */ Scancode_Push("scancode_push"), /** * 扫码推事件且弹出“消息接收中”提示框 */ Scancode_Waitmsg("scancode_waitmsg"), /** * 弹出系统拍照发图 */ Pic_SysPhoto("pic_sysphoto"), /** * 弹出拍照或者相册发图 */ Pic_Photo_OR_Album("pic_photo_or_album"), /** * 弹出微信相册发图器 */ Pic_Weixin("pic_weixin"), /** * 弹出地理位置选择器 */ Location_Select("location_select"), /** * 下发消息(除文本消息) */ Media_Id("media_id"), /** * 跳转图文消息URL */ View_Limited("view_limited"), /** * 小程序菜单 */ Miniprogram("miniprogram"); private String value = ""; ButtonType(String value) { this.value = value; } /** * @return the msgType */ @Override public String toString() { return value; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/menu/SingleButton.java
src/main/java/org/weixin4j/model/menu/SingleButton.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.menu; import java.util.ArrayList; import java.util.List; /** * 带子菜单的按钮,此按钮中必须设置子菜单 * * @author yangqisheng * @since 0.0.1 */ public class SingleButton extends BaseButton { /** * 子菜单(此菜单需要手动添加,所以get和set方法能喝微信返回的json一致) */ private List<SingleButton> subButton; public SingleButton(String name) { super(name); } /** * 设置 子菜单 * * @param sub_button 子菜单 */ public void setSubButton(List<SingleButton> sub_button) { this.subButton = sub_button; } /** * 获取 子菜单 * * @return 子菜单 */ public List<SingleButton> getSubButton() { if (subButton == null) { subButton = new ArrayList<SingleButton>(0); } return this.subButton; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/qrcode/Qrcode.java
src/main/java/org/weixin4j/model/qrcode/Qrcode.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.qrcode; /** * 二维码ticket * * @author yangqisheng * @since 0.1.0 */ public class Qrcode { /** * 获取的二维码ticket,凭借此ticket可以在有效时间内换取二维码。 */ private String ticket; /** * 二维码的有效时间,以秒为单位。最大不超过1800。 */ private int expire_seconds; /** * 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片 */ private String url; public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public int getExpire_seconds() { return expire_seconds; } public void setExpire_seconds(int expire_seconds) { this.expire_seconds = expire_seconds; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/qrcode/QrcodeType.java
src/main/java/org/weixin4j/model/qrcode/QrcodeType.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.qrcode; /** * 二维码类型 * * @author yangqisheng * @since 0.1.0 */ public enum QrcodeType { /** * 临时的整型参数值 */ QR_SCENE("QR_SCENE"), /** * 临时的字符串参数值 */ QR_STR_SCENE("QR_STR_SCENE"), /** * 永久的整型参数值 */ QR_LIMIT_SCENE("QR_LIMIT_SCENE"), /** * 永久的字符串参数值 */ QR_LIMIT_STR_SCENE("QR_LIMIT_STR_SCENE"); private String value = ""; QrcodeType(String value) { this.value = value; } @Override public String toString() { return value; } public static QrcodeType parse(String value) { if (value == null) { return null; } if (value.toUpperCase().equals(QR_SCENE.toString())) { return QR_SCENE; } if (value.toUpperCase().equals(QR_STR_SCENE.toString())) { return QR_STR_SCENE; } if (value.toUpperCase().equals(QR_LIMIT_SCENE.toString())) { return QR_LIMIT_SCENE; } if (value.toUpperCase().equals(QR_LIMIT_STR_SCENE.toString())) { return QR_LIMIT_STR_SCENE; } return null; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/model/material/Media.java
src/main/java/org/weixin4j/model/material/Media.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.model.material; import java.util.Date; import org.weixin4j.model.message.MediaType; /** * 上传成功后的素材对象 * * @author yangqisheng * @since 0.1.4 */ public class Media { /** * 媒体文件类型 * * 分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb,主要用于视频与音乐格式的缩略图) */ private MediaType mediaType; /** * 媒体文件上传后,获取标识 */ private String mediaId; /** * 媒体文件上传时间 */ private Date createdAt; public MediaType getMediaType() { return mediaType; } public void setMediaType(MediaType mediaType) { this.mediaType = mediaType; } public String getMediaId() { return mediaId; } public void setMediaId(String mediaId) { this.mediaId = mediaId; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/JsSdkComponent.java
src/main/java/org/weixin4j/component/JsSdkComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang.RandomStringUtils; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.js.Ticket; import org.weixin4j.model.js.TicketType; import org.weixin4j.model.js.WxConfig; import org.weixin4j.util.SignUtil; /** * Js接口组件 * * @author yangqisheng * @since 0.1.0 */ public class JsSdkComponent extends AbstractComponent { public JsSdkComponent(Weixin weixin) { super(weixin); } /** * 获取jsapi_ticket对象,每次都返回最新 * * @return 成功返回jsapi_ticket对象,失败返回NULL * @throws org.weixin4j.WeixinException 微信操作异常 */ public Ticket getJsApiTicket() throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取jsapi_ticket接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + weixin.getToken().getAccess_token() + "&type=jsapi"); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); //成功返回如下JSON: //{"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA","expires_in":7200} if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("获取jsapi_ticket返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { return new Ticket(TicketType.JSAPI, jsonObj.getString("ticket"), jsonObj.getIntValue("expires_in")); } } return null; } /** * 获取微信Js接口配置 * * @param url 当前网页的URL(包含?及参数,不包含#及其后面部分) * @return 微信接口配置对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public WxConfig getWxConfig(String url) throws WeixinException { String noncestr = RandomStringUtils.random(16, "abcdefghijklmnopqrstuvwxyz"); return getWxConfig(weixin.getJsApiTicket().getTicket(), noncestr, System.currentTimeMillis() / 1000, url); } /** * 获取微信Js接口配置 * * @param noncestr 随机字符串 * @param timestamp 时间戳 * @param url 当前网页的URL(包含?及参数,不包含#及其后面部分) * @return 微信接口配置对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public WxConfig getWxConfig(String noncestr, long timestamp, String url) throws WeixinException { return getWxConfig(weixin.getJsApiTicket().getTicket(), noncestr, timestamp, url); } /** * 获取微信Js接口配置 * * @param jsapi_ticket 微信JS接口的临时票据 * @param url 当前网页的URL(包含?及参数,不包含#及其后面部分) * @return 微信接口配置对象 */ public WxConfig getWxConfig(String jsapi_ticket, String url) { String noncestr = RandomStringUtils.random(16, "abcdefghijklmnopqrstuvwxyz"); return getWxConfig(jsapi_ticket, noncestr, System.currentTimeMillis() / 1000, url); } /** * 获取微信Js接口配置 * * @param jsapi_ticket 微信JS接口的临时票据 * @param noncestr 随机字符串 * @param timestamp 时间戳 * @param url 当前网页的URL(包含?及参数,不包含#及其后面部分) * @return 微信接口配置对象 */ public WxConfig getWxConfig(String jsapi_ticket, String noncestr, long timestamp, String url) { //获取jsapi签名 String sign = SignUtil.getSignature(jsapi_ticket, noncestr, timestamp + "", url); //返回微信js配置 WxConfig wxConfig = new WxConfig(); wxConfig.setAppId(weixin.getAppId()); wxConfig.setNonceStr(noncestr); wxConfig.setTimestamp(timestamp + ""); wxConfig.setSignature(sign); return wxConfig; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/MaterialComponent.java
src/main/java/org/weixin4j/component/MaterialComponent.java
package org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import java.io.File; import java.io.IOException; import java.util.Date; import org.apache.commons.lang.WordUtils; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpClient; import org.weixin4j.http.HttpsClient; import org.weixin4j.model.material.Media; import org.weixin4j.model.media.Attachment; import org.weixin4j.model.message.MediaType; /** * 素材组件 * * @author yangqisheng * @since 0.1.0 */ public class MaterialComponent extends AbstractComponent { public MaterialComponent(Weixin weixin) { super(weixin); } /** * 新增临时素材 * * @param mediaType 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) * @param file form-data中媒体文件标识,有filename、filelength、content-type等信息 * @return 上传成功返回素材Id,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.4 */ public Media upload(MediaType mediaType, File file) throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //上传素材,返回JSON数据包 String jsonStr = http.uploadHttps("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + weixin.getToken().getAccess_token() + "&type=" + mediaType.toString(), file); JSONObject jsonObj = JSONObject.parseObject(jsonStr); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("新增临时素材返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { //转换为Media对象 Media media = new Media(); media.setMediaType(MediaType.valueOf(WordUtils.capitalize(jsonObj.getString("type")))); media.setMediaId(jsonObj.getString("media_id")); //转换为毫秒数 long time = jsonObj.getLongValue("created_at") * 1000L; media.setCreatedAt(new Date(time)); //返回多媒体文件id return media; } } return null; } /** * 获取临时素材(不支持视频) * * <p> * 本接口即为原“下载多媒体文件”接口。 * </p> * * @param mediaId 媒体文件ID * @return 正确返回附件对象,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public Attachment get(String mediaId) throws WeixinException { //下载资源 String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + weixin.getToken().getAccess_token() + "&media_id=" + mediaId; //创建请求对象 HttpsClient http = new HttpsClient(); return http.downloadHttps(url); } /** * 高清语音素材获取接口 * * <p> * 可以使用本接口获取从JSSDK的uploadVoice接口上传的临时语音素材,格式为speex,16K采样率。 * </p> * * @param mediaId 媒体文件ID * @return 正确返回附件对象,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public Attachment getJssdkVoice(String mediaId) throws WeixinException { //下载资源 String url = "https://api.weixin.qq.com/cgi-bin/media/get/jssdk?access_token=" + weixin.getToken().getAccess_token() + "&media_id=" + mediaId; //创建请求对象 HttpsClient http = new HttpsClient(); return http.downloadHttps(url); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/MenuComponent.java
src/main/java/org/weixin4j/component/MenuComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import org.weixin4j.Configuration; import org.weixin4j.model.menu.Menu; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; /** * 自定义菜单组件 * * @author yangqisheng * @since 0.1.0 */ public class MenuComponent extends AbstractComponent { public MenuComponent(Weixin weixin) { super(weixin); } /** * 创建自定义菜单 * * @param menu 菜单对象 * @throws org.weixin4j.WeixinException 微信操作异常 创建自定义菜单异常 */ public void create(Menu menu) throws WeixinException { //内部业务验证 if (menu == null || menu.getButton() == null) { throw new IllegalArgumentException("menu can't be null or menu.button can't be null"); } //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + weixin.getToken().getAccess_token(), menu.toJSONObject()); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/menu/create返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 查询自定义菜单 * * @return 自定义菜单对象 * @throws org.weixin4j.WeixinException 微信操作异常 查询自定义菜单对象异常 */ public Menu get() throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + weixin.getToken().getAccess_token(), null); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/menu/get返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //返回自定义菜单对象 return new Menu(jsonObj); } //返回自定义菜单对 return null; } /** * 删除自定义菜单 * * @throws org.weixin4j.WeixinException 微信操作异常 删除自定义菜单异常 */ public void delete() throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + weixin.getToken().getAccess_token()); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/menu/delete返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/FileComponent.java
src/main/java/org/weixin4j/component/FileComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import java.io.File; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.model.media.Attachment; import org.weixin4j.http.HttpClient; /** * 文件组件,已过时,推荐使用Media组件 * * @author yangqisheng * @since 0.1.0 */ @Deprecated public class FileComponent extends AbstractComponent { public FileComponent(Weixin weixin) { super(weixin); } /** * 上传媒体文件 * * @param mediaType 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) * @param file form-data中媒体文件标识,有filename、filelength、content-type等信息 * @return 上传成功返回素材Id,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ @Deprecated public String upload(String mediaType, File file) throws WeixinException { try { //创建请求对象 HttpClient http = new HttpClient(); //上传素材,返回JSON数据包 String jsonStr = http.upload("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + weixin.getToken().getAccess_token() + "&type=" + mediaType, file); JSONObject jsonObj = JSONObject.parseObject(jsonStr); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("上传多媒体文件返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { //返回多媒体文件id return jsonObj.getString("media_id"); } } return null; } catch (IOException ex) { throw new WeixinException("上传多媒体文件异常:", ex); } catch (NoSuchAlgorithmException ex) { throw new WeixinException("上传多媒体文件异常:", ex); } catch (NoSuchProviderException ex) { throw new WeixinException("上传多媒体文件异常:", ex); } catch (KeyManagementException ex) { throw new WeixinException("上传多媒体文件异常:", ex); } catch (NumberFormatException ex) { throw new WeixinException("上传多媒体文件异常:", ex); } catch (WeixinException ex) { throw new WeixinException("上传多媒体文件异常:", ex); } } /** * 下载多媒体文件 * * @param mediaId 媒体文件ID * @return 正确返回附件对象,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ @Deprecated public Attachment download(String mediaId) throws WeixinException { try { //下载资源 String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + weixin.getToken().getAccess_token() + "&media_id=" + mediaId; //创建请求对象 HttpClient http = new HttpClient(); return http.download(url); } catch (IOException ex) { throw new WeixinException("下载多媒体文件异常:", ex); } } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/UserComponent.java
src/main/java/org/weixin4j/component/UserComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.weixin4j.Configuration; import org.weixin4j.model.user.Data; import org.weixin4j.model.user.Followers; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.user.User; /** * 用户管理组件 * * @author yangqisheng * @since 0.1.0 */ public class UserComponent extends AbstractComponent { public UserComponent(Weixin weixin) { super(weixin); } /** * 设置用户备注名 * * @param openid 用户标识 * @param remark 新的备注名,长度必须小于30字符 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void updateRemark(String openid, String remark) throws WeixinException { //内部业务验证 if (StringUtils.isEmpty(openid)) { throw new IllegalArgumentException("openid can't be null or empty"); } if (StringUtils.isEmpty(remark)) { throw new IllegalArgumentException("remark can't be null or empty"); } //拼接参数 JSONObject postParam = new JSONObject(); postParam.put("openid", openid); postParam.put("remark", remark); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=" + weixin.getToken().getAccess_token(), postParam); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { throw new WeixinException(getCause(-1)); } if (Configuration.isDebug()) { System.out.println("updateremark返回json:" + jsonObj.toString()); } //判断是否修改成功 //正常时返回 {"errcode": 0, "errmsg": "ok"} //错误时返回 示例:{"errcode":40013,"errmsg":"invalid appid"} int errcode = jsonObj.getIntValue("errcode"); //登录成功,设置accessToken和过期时间 if (errcode != 0) { //返回异常信息 throw new WeixinException(getCause(errcode)); } } /** * 获取用户基本信息(包括UnionID机制) * * @param openid 普通用户的标识,对当前公众号唯一 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public User info(String openid) throws WeixinException { //默认简体中文 return info(openid, "zh_CN"); } /** * 获取用户基本信息(包括UnionID机制) * * @param openid 普通用户的标识,对当前公众号唯一 * @param lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public User info(String openid, String lang) throws WeixinException { if (StringUtils.isEmpty(openid)) { throw new IllegalArgumentException("openid can't be null or empty"); } if (StringUtils.isEmpty(lang)) { throw new IllegalArgumentException("lang can't be null or empty"); } //拼接参数 String param = "?access_token=" + weixin.getToken().getAccess_token() + "&openid=" + openid + "&lang=" + lang; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/info" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { return null; } if (Configuration.isDebug()) { System.out.println("getUser返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //设置公众号信息 return JSONObject.toJavaObject(jsonObj, User.class); } /** * 获取用户基本信息(包括UnionID机制) * * @param openids 普通用户的标识数组,对当前公众号唯一 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public List<User> batchGet(String[] openids) throws WeixinException { if (openids == null || openids.length == 0) { throw new IllegalArgumentException("openids can't be null or empty"); } return batchGet(openids, "zh_CN"); } /** * 获取用户基本信息(包括UnionID机制) * * @param openids 普通用户的标识数组,对当前公众号唯一 * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public List<User> batchGet(String[] openids, String lang) throws WeixinException { if (StringUtils.isEmpty(lang)) { throw new IllegalArgumentException("lang can't be null or empty"); } String[] langs = new String[openids.length]; for (int i = 0; i < langs.length; i++) { langs[i] = lang; } return batchGet(openids, langs); } /** * 获取用户基本信息(包括UnionID机制) * * @param openids 普通用户的标识数组,对当前公众号唯一 * @param langs 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public List<User> batchGet(String[] openids, String[] langs) throws WeixinException { //内部业务验证 if (openids == null || openids.length == 0) { throw new IllegalArgumentException("openids can't be null or empty"); } if (langs == null || langs.length == 0) { throw new IllegalArgumentException("langs can't be null or empty"); } if (openids.length != langs.length) { throw new IllegalArgumentException("openids length are not same to langs length"); } //拼接参数 JSONObject postUserList = new JSONObject(); JSONArray userList = new JSONArray(); for (int i = 0; i < openids.length; i++) { JSONObject postUser = new JSONObject(); postUser.put("openid", openids[i]); postUser.put("lang", langs[i]); userList.add(postUser); } postUserList.put("user_list", userList); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" + weixin.getToken().getAccess_token(), postUserList); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { return null; } if (Configuration.isDebug()) { System.out.println("batchGetUser返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //获取用户列表 JSONArray userlistArray = jsonObj.getJSONArray("user_info_list"); List<User> users = new ArrayList<User>(); for (Object userObj : userlistArray) { //转换为User对象 users.add(JSONObject.toJavaObject((JSONObject) userObj, User.class)); } return users; } /** * 获取所有用户列表 * * 公众号粉丝数量超过1万,推荐使用请分页获取。 * * @return 关注者列表对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Followers getAll() throws WeixinException { Followers allFollower = new Followers(); int toatl = 0; int count = 0; Data data = new Data(); data.setOpenid(new ArrayList<String>()); allFollower.setData(data); String next_openid = ""; do { Followers f = get(next_openid); if (f == null) { break; } if (f.getCount() > 0) { count += f.getCount(); toatl += f.getTotal(); List<String> openids = f.getData().getOpenid(); for (String openid : openids) { allFollower.getData().getOpenid().add(openid); } } next_openid = f.getNext_openid(); } while (next_openid != null && !next_openid.equals("")); allFollower.setCount(count); allFollower.setTotal(toatl); return allFollower; } /** * 获取用户列表 * * @param next_openid 第一个拉取的OPENID,不填默认从头开始拉取 * @return 关注者列表对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Followers get(String next_openid) throws WeixinException { //拼接参数 String param = "?access_token=" + weixin.getToken().getAccess_token() + "&next_openid="; //第一次获取不添加参数 if (next_openid != null && !next_openid.equals("")) { param += next_openid; } //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/get" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { return null; } if (Configuration.isDebug()) { System.out.println("getUserList返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } return (Followers) JSONObject.toJavaObject(jsonObj, Followers.class); } /** * 获取标签下所有粉丝列表 * * @param tagid 标签ID * @return 关注者对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Followers tagGetAll(int tagid) throws WeixinException { Followers allFollower = new Followers(); int toatl = 0; int count = 0; Data data = new Data(); data.setOpenid(new ArrayList<String>()); allFollower.setData(data); String next_openid = ""; do { Followers f = tagGet(tagid, next_openid); if (f == null) { break; } if (f.getCount() > 0) { count += f.getCount(); toatl += f.getTotal(); List<String> openids = f.getData().getOpenid(); for (String openid : openids) { allFollower.getData().getOpenid().add(openid); } } next_openid = f.getNext_openid(); } while (next_openid != null && !next_openid.equals("")); allFollower.setCount(count); allFollower.setTotal(toatl); return allFollower; } /** * 获取标签下粉丝列表 * * <p> * 通过公众号,返回用户对象,进行用户相关操作</p> * * @param tagid 标签ID * @param next_openid 第一个拉取的OPENID,不填默认从头开始拉取 * @return 关注者对象 * @throws org.weixin4j.WeixinException 微信操作异常 when Weixin service or network is unavailable, or * the user has not authorized */ public Followers tagGet(int tagid, String next_openid) throws WeixinException { //拼接参数 String param = "?access_token=" + weixin.getToken().getAccess_token() + "&tagid=" + tagid + "&next_openid="; //第一次获取不添加参数 if (next_openid != null && !next_openid.equals("")) { param += next_openid; } //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取标签下粉丝列表接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/tag/get" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); Followers follower = null; if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("getTagUserList返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } follower = (Followers) JSONObject.toJavaObject(jsonObj, Followers.class); } return follower; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/GroupsComponent.java
src/main/java/org/weixin4j/component/GroupsComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.groups.Group; /** * 用户分组组件(微信已过时,推荐使用标签组件) * * @author yangqisheng * @since 0.1.0 */ public class GroupsComponent extends AbstractComponent { public GroupsComponent(Weixin weixin) { super(weixin); } /** * 创建分组 * * @param name 分组名字(30个字符以内) * @return 创建成功,返回带Id的Group对象 * @throws org.weixin4j.WeixinException 创建分组异常 */ public Group create(String name) throws WeixinException { //内部业务验证 if (name == null || name.equals("")) { throw new IllegalStateException("name can not be null or empty"); } //拼接参数 JSONObject postGroup = new JSONObject(); JSONObject postName = new JSONObject(); postName.put("name", name); postGroup.put("group", postName); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/groups/create?access_token=" + weixin.getToken().getAccess_token(), postGroup); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); Group group = null; if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/groups/create返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } JSONObject jsonGroup = jsonObj.getJSONObject("group"); group = JSONObject.toJavaObject(jsonGroup, Group.class); } return group; } /** * 查询所有分组 * * <p> * 最多支持创建500个分组</p> * * @return 分组列表 * @throws org.weixin4j.WeixinException 查询所有分组异常 */ public List<Group> get() throws WeixinException { List<Group> groupList = new ArrayList<Group>(); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + weixin.getToken().getAccess_token(), null); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("getGroups返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //获取分组列表 JSONArray groups = jsonObj.getJSONArray("groups"); for (int i = 0; i < groups.size(); i++) { JSONObject jsonGroup = groups.getJSONObject(i); Group group = (Group) JSONObject.toJavaObject(jsonGroup, Group.class); groupList.add(group); } } return groupList; } /** * 查询用户所在分组 * * <p> * 通过用户的OpenID查询其所在的GroupID</p> * * @param openid 用户唯一标识符 * @return 返回用户所在分组Id * @throws org.weixin4j.WeixinException 查询用户所在分组异常 */ public int getId(String openid) throws WeixinException { //内部业务验证 if (openid == null || openid.equals("")) { throw new IllegalStateException("openid is null!"); } int groupId = -1; //拼接参数 JSONObject postParam = new JSONObject(); postParam.put("openid", openid); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=" + weixin.getToken().getAccess_token(), postParam); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("getGroupId返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //获取成功返回分组Id groupId = jsonObj.getIntValue("groupid"); } return groupId; } /** * 修改分组名 * * @param id 分组id,由微信分配 * @param name 分组名字(30个字符以内) * @throws org.weixin4j.WeixinException 修改分组名异常 */ public void update(int id, String name) throws WeixinException { //内部业务验证 if (id < 0) { throw new IllegalStateException("id can not <= 0!"); } if (name == null || name.equals("")) { throw new IllegalStateException("name is null!"); } //拼接参数 JSONObject postGroup = new JSONObject(); JSONObject postName = new JSONObject(); postName.put("id", id); postName.put("name", name); postGroup.put("group", postName); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/groups/update?access_token=" + weixin.getToken().getAccess_token(), postGroup); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/groups/update返回json:" + jsonObj.toString()); } //判断是否修改成功 //正常时返回 {"errcode": 0, "errmsg": "ok"} //错误时返回 示例:{"errcode":40013,"errmsg":"invalid appid"} int errcode = jsonObj.getIntValue("errcode"); //登录成功,设置accessToken和过期时间 if (errcode != 0) { //返回异常信息 throw new WeixinException(getCause(errcode)); } } } /** * 删除分组 * * @param groupId 分组Id * @throws org.weixin4j.WeixinException 删除分组异常 */ public void delete(int groupId) throws WeixinException { //拼接参数 JSONObject postParam = new JSONObject(); JSONObject group = new JSONObject(); group.put("id", groupId); postParam.put("group", group); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=" + weixin.getToken().getAccess_token(), postParam); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/groups/delete返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 移动用户分组 * * @param openid 用户唯一标识符 * @param to_groupid 分组id * @throws org.weixin4j.WeixinException 移动用户分组异常 */ public void membersUpdate(String openid, int to_groupid) throws WeixinException { //内部业务验证 if (openid == null || openid.equals("")) { throw new IllegalStateException("openid is null!"); } if (to_groupid < 0) { throw new IllegalStateException("to_groupid can not <= 0!"); } //拼接参数 JSONObject postParam = new JSONObject(); postParam.put("openid", openid); postParam.put("to_groupid", to_groupid); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" + weixin.getToken().getAccess_token(), postParam); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/groups/members/update返回json:" + jsonObj.toString()); } //判断是否修改成功 //正常时返回 {"errcode": 0, "errmsg": "ok"} //错误时返回 示例:{"errcode":40013,"errmsg":"invalid appid"} int errcode = jsonObj.getIntValue("errcode"); //登录成功,设置accessToken和过期时间 if (errcode != 0) { //返回异常信息 throw new WeixinException(getCause(errcode)); } } } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/AbstractComponent.java
src/main/java/org/weixin4j/component/AbstractComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import org.weixin4j.Weixin; import org.weixin4j.WeixinSupport; /** * 微信组件基础类 * * @author yangqisheng * @since 0.1.0 */ public abstract class AbstractComponent extends WeixinSupport{ protected Weixin weixin; public AbstractComponent(Weixin weixin) { if (weixin == null) { throw new IllegalArgumentException("weixin can not be null"); } this.weixin = weixin; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/BaseComponent.java
src/main/java/org/weixin4j/component/BaseComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.List; import org.apache.commons.lang.StringUtils; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.base.Token; /** * 基础组件 * * @author yangqisheng * @since 0.1.0 */ public class BaseComponent extends AbstractComponent { public BaseComponent(Weixin weixin) { super(weixin); } /** * 获取access_token(每次都获取新的,请缓存下来,2小时过期) * * @return 获取的AccessToken对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Token token() throws WeixinException { if (StringUtils.isEmpty(weixin.getAppId())) { throw new IllegalArgumentException("appid can't be null or empty"); } if (StringUtils.isEmpty(weixin.getSecret())) { throw new IllegalArgumentException("secret can't be null or empty"); } //拼接参数 String param = "?grant_type=client_credential&appid=" + weixin.getAppId() + "&secret=" + weixin.getSecret(); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/token" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { throw new WeixinException(getCause(-1)); } if (Configuration.isDebug()) { System.out.println("getAccessToken返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //设置凭证,设置accessToken和过期时间 //update at 0.1.6 因为 fastjson 1.2.68 直接转换JSON不走set方法 return new Token(jsonObj); } /** * 将一条长链接转成短链接 * * @param long_url 长链接 * @return 短链接 * @throws org.weixin4j.WeixinException 微信操作异常 */ public String shortUrl(String long_url) throws WeixinException { if (StringUtils.isEmpty(long_url)) { throw new IllegalStateException("long_url can not be null or empty"); } JSONObject postJson = new JSONObject(); postJson.put("action", "long2short"); postJson.put("long_url", long_url); HttpsClient http = new HttpsClient(); //调用创建Tick的access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" + weixin.getToken().getAccess_token(), postJson); //根据请求结果判定,返回结果 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { throw new WeixinException(getCause(-1)); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { return jsonObj.getString("short_url"); } } /** * 获取微信服务器IP地址 * * @return 微信服务器IP地址列表 * @throws org.weixin4j.WeixinException 微信操作异常 */ public List<String> getCallbackIp() throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取微信服务器IP接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + weixin.getToken().getAccess_token()); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); //成功返回如下JSON: //{"ip_list":["127.0.0.1","127.0.0.1"]} if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("获取getCallbackIp返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { JSONArray ipList = jsonObj.getJSONArray("ip_list"); if (ipList != null) { //转换为List List ips = ipList.subList(0, ipList.size()); return (List<String>) ips; } } } return null; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/RedpackComponent.java
src/main/java/org/weixin4j/component/RedpackComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.redpack.SendRedPack; import org.weixin4j.model.redpack.SendRedPackResult; /** * 红包组件 * * @author yangqisheng * @since 0.1.0 */ public class RedpackComponent extends AbstractComponent { public RedpackComponent(Weixin weixin) { super(weixin); } /** * 发送现金红包 * * <p> * 使用weixin4j.properties的配置</p> * * @param sendRedPack 现金红包对象 * @return 发送现金红包返回结果对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public SendRedPackResult sendRedPack(SendRedPack sendRedPack) throws WeixinException { String certPath = this.weixin.getWeixinPayConfig().getCertPath(); String certSecret = this.weixin.getWeixinPayConfig().getCertSecret(); return sendRedPack(sendRedPack, certPath, certSecret); } /** * 发送现金红包 * * <p> * mchId字段无效,传或不传已不影响结果 * </p> * * @param sendRedPack 现金红包对象 * @param mchId 商户号 * @param certPath 证书路径 * @param certSecret 证书密钥 * @return 发送现金红包返回结果对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ @Deprecated public SendRedPackResult sendRedPack(SendRedPack sendRedPack, String mchId, String certPath, String certSecret) throws WeixinException { return sendRedPack(sendRedPack, certPath, certSecret); } /** * 发送现金红包 * * @param sendRedPack 现金红包对象 * @param certPath 证书路径 * @param certSecret 证书密钥 * @return 发送现金红包返回结果对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public SendRedPackResult sendRedPack(SendRedPack sendRedPack, String certPath, String certSecret) throws WeixinException { //将统一下单对象转成XML String xmlPost = sendRedPack.toXML(); if (Configuration.isDebug()) { System.out.println("调试模式_发送现金红包接口 提交XML数据:" + xmlPost); } //创建请求对象 HttpsClient http = new HttpsClient(); //提交xml格式数据 Response res = http.postXml("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack", xmlPost, certPath, certSecret); //获取微信平台下单接口返回数据 String xmlResult = res.asString(); try { JAXBContext context = JAXBContext.newInstance(SendRedPackResult.class); Unmarshaller unmarshaller = context.createUnmarshaller(); SendRedPackResult result = (SendRedPackResult) unmarshaller.unmarshal(new StringReader(xmlResult)); return result; } catch (JAXBException ex) { return null; } } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/MediaComponent.java
src/main/java/org/weixin4j/component/MediaComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import java.io.File; import java.io.IOException; import java.util.List; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpClient; import org.weixin4j.model.media.Attachment; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.media.Article; import org.weixin4j.model.message.MediaType; /** * 多媒体组件,已过时,推荐使用Material组件 * * @author yangqisheng * @since 0.1.0 */ @Deprecated public class MediaComponent extends AbstractComponent { public MediaComponent(Weixin weixin) { super(weixin); } /** * 上传图文消息内的图片获取URL * * <p> * 请注意,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。 <br> * 图片仅支持jpg/png格式,大小必须在1MB以下。 * </p> * * @param file form-data中媒体文件标识,有filename、filelength、content-type等信息 * @return 上传成功返回图文素材Id,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public String uploadimg(File file) throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //上传素材,返回JSON数据包 String jsonStr = http.uploadHttps("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" + weixin.getToken().getAccess_token(), file); JSONObject jsonObj = JSONObject.parseObject(jsonStr); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("上传图文消息内的图片返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { //返回图片Url return jsonObj.getString("url"); } } return null; } /** * 上传图文消息素材 * * @param articles 图文消息,一个图文消息支持1到8条图文 * @return 上传成功返回图文素材Id,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public String uploadnews(List<Article> articles) throws WeixinException { JSONObject json = new JSONObject(); json.put("articles", articles); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("uploadnews返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { //返回图文消息id return jsonObj.getString("media_id"); } } return null; } /** * 新增临时素材 * * @param mediaType 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) * @param file form-data中媒体文件标识,有filename、filelength、content-type等信息 * @return 上传成功返回素材Id,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public String upload(MediaType mediaType, File file) throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //上传素材,返回JSON数据包 String jsonStr = http.uploadHttps("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + weixin.getToken().getAccess_token() + "&type=" + mediaType.toString(), file); JSONObject jsonObj = JSONObject.parseObject(jsonStr); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("上传多媒体文件返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { //返回多媒体文件id return jsonObj.getString("media_id"); } } return null; } /** * 获取临时素材 * * <p> * 本接口即为原“下载多媒体文件”接口。 * </p> * * @param mediaId 媒体文件ID * @return 正确返回附件对象,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public Attachment get(String mediaId) throws WeixinException { //下载资源 String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + weixin.getToken().getAccess_token() + "&media_id=" + mediaId; //创建请求对象 HttpsClient http = new HttpsClient(); return http.downloadHttps(url); } /** * 获取视频下载地址 * * @param mediaId 视频媒体文件ID * @return 正确返回附件对象,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public String getVideoUrl(String mediaId) throws WeixinException { try { //下载资源,请注意,视频文件不支持https下载,调用该接口需http协议。 String url = "http://api.weixin.qq.com/cgi-bin/media/get?access_token=" + weixin.getToken().getAccess_token() + "&media_id=" + mediaId; //创建请求对象 HttpClient http = new HttpClient(); Attachment attachment = http.download(url); //返回附件全名 return attachment.getFullName(); } catch (IOException ex) { throw new WeixinException("获取视频下载地址异常:", ex); } } /** * 高清语音素材获取接口 * * <p> * 可以使用本接口获取从JSSDK的uploadVoice接口上传的临时语音素材,格式为speex,16K采样率。 * </p> * * @param mediaId 媒体文件ID * @return 正确返回附件对象,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public Attachment getJssdkVoice(String mediaId) throws WeixinException { //下载资源 String url = "https://api.weixin.qq.com/cgi-bin/media/get/jssdk?access_token=" + weixin.getToken().getAccess_token() + "&media_id=" + mediaId; //创建请求对象 HttpsClient http = new HttpsClient(); return http.downloadHttps(url); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/QrcodeComponent.java
src/main/java/org/weixin4j/component/QrcodeComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.weixin4j.http.Response; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.commons.lang.StringUtils; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.model.qrcode.Qrcode; import org.weixin4j.model.qrcode.QrcodeType; /** * 生成带参数的二维码 * * @author yangqisheng * @since 0.1.0 */ public class QrcodeComponent extends AbstractComponent { public QrcodeComponent(Weixin weixin) { super(weixin); } /** * 创建二维码ticket,整型值 * * @param qrcodeType 二维码类型 * @param scene_id 场景值ID * @param expire_seconds 临时二维码过期时间 * @return 二维码ticket * @throws org.weixin4j.WeixinException 微信操作异常 */ public Qrcode create(QrcodeType qrcodeType, int scene_id, int expire_seconds) throws WeixinException { return create(qrcodeType, scene_id, null, expire_seconds); } /** * 创建二维码ticket,字符串值 * * @param qrcodeType 二维码类型 * @param scene_str 场景值ID * @param expire_seconds 临时二维码过期时间 * @return 二维码ticket * @throws org.weixin4j.WeixinException 微信操作异常 */ public Qrcode create(QrcodeType qrcodeType, String scene_str, int expire_seconds) throws WeixinException { return create(qrcodeType, 0, scene_str, expire_seconds); } /** * 创建永久二维码ticket,整型值 * * @param scene_id 场景值ID * @return 二维码ticket * @throws org.weixin4j.WeixinException 微信操作异常 */ public Qrcode createLimit(int scene_id) throws WeixinException { return create(QrcodeType.QR_LIMIT_SCENE, scene_id, null, 0); } /** * 创建永久二维码ticket,字符串值 * * @param scene_str 场景值ID * @return 二维码ticket * @throws org.weixin4j.WeixinException 微信操作异常 */ public Qrcode createLimit(String scene_str) throws WeixinException { return create(QrcodeType.QR_LIMIT_STR_SCENE, 0, scene_str, 0); } //内部公用方法 private Qrcode create(QrcodeType qrcodeType, int scene_id, String scene_str, int expire_seconds) throws WeixinException { JSONObject scene = new JSONObject(); //内部业务验证 switch (qrcodeType) { case QR_SCENE: if (scene_id <= 0) { throw new IllegalStateException("场景id不能小于等于0"); } scene.put("scene_id", scene_id); break; case QR_LIMIT_SCENE: if (scene_id <= 0 || scene_id > 100000) { throw new IllegalStateException("永久场景id参数只支持1-100000"); } scene.put("scene_id", scene_id); break; case QR_STR_SCENE: case QR_LIMIT_STR_SCENE: if (StringUtils.isEmpty(scene_str)) { throw new IllegalStateException("场景scene_str不能为空"); } scene.put("scene_str", scene_str); break; default: throw new IllegalStateException("场景类型错误"); } JSONObject ticketJson = new JSONObject(); if (qrcodeType.equals(QrcodeType.QR_SCENE) || qrcodeType.equals(QrcodeType.QR_STR_SCENE)) { //临时二维码过期时间 ticketJson.put("expire_seconds", expire_seconds); } //二维码类型 ticketJson.put("action_name", qrcodeType.toString()); //帐号信息 JSONObject actionInfo = new JSONObject(); actionInfo.put("scene", scene); //二维码详细信息 ticketJson.put("action_info", actionInfo); //创建请求对象 HttpsClient http = new HttpsClient(); //调用创建Tick的access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + weixin.getToken().getAccess_token(), ticketJson); //根据请求结果判定,返回结果 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/qrcode/create返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { return JSONObject.toJavaObject(jsonObj, Qrcode.class); } } return null; } /** * 通过ticket换取二维码链接 * * @param ticket 获取的二维码ticket * @return 二维码链接,或抛WechatException * @throws org.weixin4j.WeixinException 微信操作异常 */ public String showQrcode(String ticket) throws WeixinException { try { return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLEncoder.encode(ticket, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new WeixinException(e); } } /** * 保存二维码 * * @param ticket 获取的二维码ticket * @param filePath 保存的地址 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void saveQrcode(String ticket, String filePath) throws WeixinException { try { //通过ticket换取二维码 URL url = new URL("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket); // 打开连接 URLConnection con = url.openConnection(); // 输入流 InputStream is = con.getInputStream(); // 1K的数据缓冲 byte[] bs = new byte[1024]; // 读取到的数据长度 int len; // 输出的文件流 OutputStream os = new FileOutputStream(filePath); // 开始读取 while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } // 完毕,关闭所有链接 os.close(); is.close(); } catch (MalformedURLException ex) { throw new WeixinException("通过ticket换取二维码异常:", ex); } catch (IOException ex) { throw new WeixinException("通过ticket换取二维码,下载二维码图片异常:", ex); } } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/PayComponent.java
src/main/java/org/weixin4j/component/PayComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.pay.OrderQuery; import org.weixin4j.model.pay.OrderQueryResult; import org.weixin4j.model.pay.UnifiedOrder; import org.weixin4j.model.pay.UnifiedOrderResult; import org.weixin4j.model.pay.UnifiedOrderSL; import org.weixin4j.model.pay.UnifiedOrderSLResult; /** * 支付组件 * * @author yangqisheng * @since 0.1.0 */ public class PayComponent extends AbstractComponent { public PayComponent(Weixin weixin) { super(weixin); } /** * 统一下单 * * @param unifiedorder 统一下单对象 * @return 下单返回结果对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public UnifiedOrderResult payUnifiedOrder(UnifiedOrder unifiedorder) throws WeixinException { //将统一下单对象转成XML String xmlPost = unifiedorder.toXML(); if (Configuration.isDebug()) { System.out.println("调试模式_统一下单接口 提交XML数据:" + xmlPost); } //创建请求对象 HttpsClient http = new HttpsClient(); //提交xml格式数据 Response res = http.postXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlPost); //获取微信平台下单接口返回数据 String xmlResult = res.asString(); try { JAXBContext context = JAXBContext.newInstance(UnifiedOrderResult.class); Unmarshaller unmarshaller = context.createUnmarshaller(); UnifiedOrderResult result = (UnifiedOrderResult) unmarshaller.unmarshal(new StringReader(xmlResult)); return result; } catch (JAXBException ex) { return null; } } /** * 服务商统一下单 * * @param unifiedOrderSL 统一下单对象 * @return 下单返回结果对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public UnifiedOrderSLResult payUnifiedOrderSL(UnifiedOrderSL unifiedOrderSL) throws WeixinException { //将统一下单对象转成XML String xmlPost = unifiedOrderSL.toXML(); if (Configuration.isDebug()) { System.out.println("调试模式_服务商统一下单接口 提交XML数据:" + xmlPost); } //创建请求对象 HttpsClient http = new HttpsClient(); //提交xml格式数据 Response res = http.postXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlPost); //获取微信平台下单接口返回数据 String xmlResult = res.asString(); try { JAXBContext context = JAXBContext.newInstance(UnifiedOrderSLResult.class); Unmarshaller unmarshaller = context.createUnmarshaller(); UnifiedOrderSLResult result = (UnifiedOrderSLResult) unmarshaller.unmarshal(new StringReader(xmlResult)); return result; } catch (JAXBException ex) { return null; } } /** * 查询订单 * * @param orderQuery 订单查询对象 * @return 订单查询结果 * @throws org.weixin4j.WeixinException 微信操作异常 */ public OrderQueryResult payOrderQuery(OrderQuery orderQuery) throws WeixinException { //将统一下单对象转成XML String xmlPost = orderQuery.toXML(); if (Configuration.isDebug()) { System.out.println("调试模式_查询订单接口 提交XML数据:" + xmlPost); } //创建请求对象 HttpsClient http = new HttpsClient(); //提交xml格式数据 Response res = http.postXml("https://api.mch.weixin.qq.com/pay/orderquery", xmlPost); //获取微信平台查询订单接口返回数据 String xmlResult = res.asString(); try { if (Configuration.isDebug()) { System.out.println("调试模式_查询订单接口 接收XML数据:" + xmlResult); } JAXBContext context = JAXBContext.newInstance(OrderQueryResult.class); Unmarshaller unmarshaller = context.createUnmarshaller(); OrderQueryResult result = (OrderQueryResult) unmarshaller.unmarshal(new StringReader(xmlResult)); return result; } catch (JAXBException ex) { return null; } } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/TagsComponent.java
src/main/java/org/weixin4j/component/TagsComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.tags.Tag; /** * 用户标签管理组件 * * @author yangqisheng * @since 0.1.0 */ public class TagsComponent extends AbstractComponent { public TagsComponent(Weixin weixin) { super(weixin); } /** * 创建标签 * * <p> * 一个公众号,最多可以创建100个标签。</p> * * @param name 标签名,UTF8编码 * @return 包含标签ID的对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Tag create(String name) throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //拼接参数 JSONObject postTag = new JSONObject(); JSONObject postName = new JSONObject(); postName.put("name", name); postTag.put("tag", postName); //调用获创建标签接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/create?access_token=" + weixin.getToken().getAccess_token(), postTag); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); //成功返回如下JSON: //{"tag":{"id":134, name":"广东"}} if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("获取/tags/create返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { JSONObject tagJson = jsonObj.getJSONObject("tag"); if (tagJson != null) { return JSONObject.toJavaObject(tagJson, Tag.class); } } } return null; } /** * 获取公众号已创建的标签 * * @return 公众号标签列表 * @throws org.weixin4j.WeixinException 微信操作异常 */ public List<Tag> get() throws WeixinException { List<Tag> tagList = new ArrayList<Tag>(); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取jsapi_ticket接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/tags/get?access_token=" + weixin.getToken().getAccess_token()); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); //成功返回如下JSON: //{"tags":[{"id":1,"name":"黑名单","count":0},{"id":2,"name":"星标组","count":0},{"id":127,"name":"广东","count":5}]} if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("获取/tags/get返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { JSONArray tags = jsonObj.getJSONArray("tags"); if (tags != null) { for (int i = 0; i < tags.size(); i++) { JSONObject jsonTag = tags.getJSONObject(i); Tag tag = (Tag) JSONObject.toJavaObject(jsonTag, Tag.class); tagList.add(tag); } } } } return tagList; } /** * 编辑标签 * * @param id 标签id,由微信分配 * @param name 标签名,UTF8编码(30个字符以内) * @throws org.weixin4j.WeixinException 微信操作异常 编辑标签异常 */ public void update(int id, String name) throws WeixinException { //内部业务验证 if (id < 0) { throw new IllegalStateException("id can not <= 0!"); } if (name == null || name.equals("")) { throw new IllegalStateException("name is null!"); } //拼接参数 JSONObject postTag = new JSONObject(); JSONObject postName = new JSONObject(); postName.put("id", id); postName.put("name", name); postTag.put("tag", postName); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/update?access_token=" + weixin.getToken().getAccess_token(), postTag); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/tags/update返回json:" + jsonObj.toString()); } //判断是否修改成功 //正常时返回 {"errcode": 0, "errmsg": "ok"} //错误时返回 示例:{"errcode":45158,"errmsg":"标签名长度超过30个字节"} int errcode = jsonObj.getIntValue("errcode"); //登录成功,设置accessToken和过期时间 if (errcode != 0) { //返回异常信息 throw new WeixinException(getCause(errcode)); } } } /** * 删除标签 * * @param id 标签Id * @throws org.weixin4j.WeixinException 微信操作异常 删除分组异常 */ public void delete(int id) throws WeixinException { //拼接参数 JSONObject postParam = new JSONObject(); JSONObject postId = new JSONObject(); postId.put("id", id); postParam.put("tag", postId); //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=" + weixin.getToken().getAccess_token(), postParam); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/tags/delete返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 批量为用户打标签 * * @param tagid 标签ID * @param openids 粉丝OpenId集合 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void membersBatchtagging(int tagid, String[] openids) throws WeixinException { JSONObject json = new JSONObject(); json.put("tagid", tagid); json.put("openid_list", openids); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/tags/members/batchtagging返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 批量为用户取消标签 * * @param tagid 标签ID * @param openids 粉丝OpenId集合 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void membersBatchuntagging(int tagid, String[] openids) throws WeixinException { JSONObject json = new JSONObject(); json.put("tagid", tagid); json.put("openid_list", openids); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/tags/members/batchuntagging返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 获取用户身上的标签列表 * * @param openid 粉丝OpenId * @return 公众号标签ID集合 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Integer[] getIdList(String openid) throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取用户身上的标签列表接口 Response res = http.get("https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=" + weixin.getToken().getAccess_token()); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); //成功返回如下JSON: //{"tagid_list":[134,2]} if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("获取/tags/getidlist返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { JSONArray tags = jsonObj.getJSONArray("tagid_list"); if (tags != null) { return tags.toArray(new Integer[]{}); } } } return null; } /** * 获取公众号的黑名单openids列表 * * @param openid 开始粉丝OpenId(首次传空) * @return 黑名单列表 * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.4 */ public String[] membersGetBlackList(String openid) throws WeixinException { //创建请求对象 HttpsClient http = new HttpsClient(); //封装请求参数 JSONObject postParam = new JSONObject(); postParam.put("begin_openid", openid); //调用获取用户身上的标签列表接口 Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist?access_token=" + weixin.getToken().getAccess_token(), postParam); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); //成功返回如下JSON: //{ // "total":23000, // "count":10000, // "data":{" // openid":[ // "OPENID1", // "OPENID2", // ..., // "OPENID10000" // ] // }, // "next_openid":"OPENID10000" //} if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("获取/tags/members/getblacklist返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { JSONObject data = jsonObj.getJSONObject("data"); if (data != null) { //获取openid集合 JSONArray arrays = data.getJSONArray("openid"); if (openid != null) { String[] openids = arrays.toArray(new String[]{}); //根据openid查询用户信息 return openids; } } } } return null; } /** * 批量拉黑用户 * * @param openids 需要拉入黑名单的用户的openid,一次拉黑最多允许20个 * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.4 */ public void membersBatchblacklist(String[] openids) throws WeixinException { JSONObject json = new JSONObject(); json.put("openid_list", openids); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/tags/members/batchblacklist返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 批量取消拉黑用户 * * @param openids 需要取消拉入黑名单的用户的openid,一次拉黑最多允许20个 * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.4 */ public void membersBatchunblacklist(String[] openids) throws WeixinException { JSONObject json = new JSONObject(); json.put("openid_list", openids); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/members/batchunblacklist?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/tags/members/batchunblacklist返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/SnsComponent.java
src/main/java/org/weixin4j/component/SnsComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import org.weixin4j.model.sns.SnsAccessToken; import org.weixin4j.http.Response; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.apache.commons.lang.StringUtils; import org.weixin4j.Configuration; import org.weixin4j.model.sns.SnsUser; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; /** * 网页授权获取用户基本信息 * * @author yangqisheng * @since 0.1.0 */ public class SnsComponent extends AbstractComponent { /** * 默认授权请求URL */ private String authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize"; /** * 网页授权基础支持 * * @param weixin 微信对象 */ public SnsComponent(Weixin weixin) { super(weixin); } /** * 开放的网页授权基础支持 * * @param weixin 微信对象 * @param authorize_url 第三方网页授权开发URL */ public SnsComponent(Weixin weixin, String authorize_url) { super(weixin); this.authorize_url = authorize_url; } /** * 静默授权获取openid * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @return 静默授权链接 */ public String getOAuth2CodeBaseUrl(String redirect_uri) { return getOAuth2CodeUrl(redirect_uri, "snsapi_base", "DEFAULT"); } /** * 网页安全授权获取用户信息 * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @return 网页安全授权链接 */ public String getOAuth2CodeUserInfoUrl(String redirect_uri) { return getOAuth2CodeUrl(redirect_uri, "snsapi_userinfo", "DEFAULT"); } /** * 获取授权链接 * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @param scope 应用授权作用域,snsapi_base * (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo * (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 ) * @param state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节 * @return 授权链接 */ public String getOAuth2CodeUrl(String redirect_uri, String scope, String state) { try { return authorize_url + "?appid=" + weixin.getAppId() + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") + "&response_type=code&scope=" + scope + "&state=" + state + "&connect_redirect=1#wechat_redirect"; } catch (UnsupportedEncodingException ex) { return ""; } } /** * 获取微信用户OpenId * * @param code 仅能使用一次 * @return 微信用户OpenId * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public String getOpenId(String code) throws WeixinException { SnsAccessToken snsAccessToken = getSnsOAuth2AccessToken(code); return snsAccessToken.getOpenid(); } /** * 获取网页授权AccessToken * * @param code 换取身份唯一凭证 * @return 网页授权AccessToken * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public SnsAccessToken getSnsOAuth2AccessToken(String code) throws WeixinException { if (StringUtils.isEmpty(code)) { throw new IllegalArgumentException("code can't be null or empty"); } //拼接参数 String param = "?appid=" + weixin.getAppId() + "&secret=" + weixin.getSecret() + "&code=" + code + "&grant_type=authorization_code"; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/oauth2/access_token" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { return null; } if (Configuration.isDebug()) { System.out.println("getSnsOAuth2AccessToken返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } return new SnsAccessToken(jsonObj); } /** * 检验授权凭证(access_token)是否有效 * * @param access_token 网页授权接口调用凭证 * @param openid 用户的唯一标识 * @return 可用返回true,否则返回false * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public boolean validateAccessToken(String access_token, String openid) throws WeixinException { if (StringUtils.isEmpty(access_token)) { throw new IllegalArgumentException("access_token can't be null or empty"); } if (StringUtils.isEmpty(openid)) { throw new IllegalArgumentException("openid can't be null or empty"); } //拼接参数 String param = "?access_token=" + access_token + "&openid=" + openid; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/auth" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("validateAccessToken返回json:" + jsonObj.toString()); } return jsonObj.getIntValue("errcode") == 0; } return false; } /** * 刷新用户网页授权AccessToken * * @param refresh_token 用户刷新access_token * @return 刷新后的用户网页授权AccessToken * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public SnsAccessToken refreshToken(String refresh_token) throws WeixinException { if (StringUtils.isEmpty(refresh_token)) { throw new IllegalArgumentException("refresh_token can't be null or empty"); } //拼接参数 String param = "?appid=" + weixin.getAppId() + "&refresh_token=" + refresh_token + "&grant_type=refresh_token"; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/oauth2/refresh_token" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("refreshToken返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //判断是否登录成功,并判断过期时间 Object obj = jsonObj.get("access_token"); //登录成功,设置accessToken和过期时间 if (obj != null) { //设置凭证 return new SnsAccessToken(jsonObj); } } return null; } /** * 拉取用户信息 * * @param code 换取身份唯一凭证 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public SnsUser getSnsUserByCode(String code) throws WeixinException { //默认简体中文 return getSnsUserByCode(code, "zh_CN"); } /** * 拉取用户信息 * * @param code 换取身份唯一凭证 * @param lang 国家地区语言版本 zh_CN 简体,zh_TW 繁体,en 英语 * @return 网页授权用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public SnsUser getSnsUserByCode(String code, String lang) throws WeixinException { if (StringUtils.isEmpty(code)) { throw new IllegalArgumentException("code can't be null or empty"); } if (StringUtils.isEmpty(lang)) { throw new IllegalArgumentException("lang can't be null or empty"); } SnsAccessToken snsAccessToken = getSnsOAuth2AccessToken(code); return getSnsUser(snsAccessToken.getAccess_token(), snsAccessToken.getOpenid(), lang); } /** * 拉取用户信息 * * @param access_token 网页授权接口调用凭证 * @param openid 用户的唯一标识 * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ private SnsUser getSnsUser(String access_token, String openid, String lang) throws WeixinException { if (StringUtils.isEmpty(access_token)) { throw new IllegalArgumentException("access_token can't be null or empty"); } if (StringUtils.isEmpty(openid)) { throw new IllegalArgumentException("openid can't be null or empty"); } if (StringUtils.isEmpty(lang)) { throw new IllegalArgumentException("lang can't be null or empty"); } SnsUser user = null; //拼接参数 String param = "?access_token=" + access_token + "&openid=" + openid + "&lang=" + lang; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/userinfo" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("getSnsUser返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //设置公众号信息 user = (SnsUser) JSONObject.toJavaObject(jsonObj, SnsUser.class); } return user; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/component/MessageComponent.java
src/main/java/org/weixin4j/component/MessageComponent.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import java.util.List; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; import org.weixin4j.http.Response; import org.weixin4j.model.message.Articles; import org.weixin4j.model.message.template.Miniprogram; import org.weixin4j.model.message.template.TemplateData; import org.weixin4j.model.message.template.TemplateMessage; /** * 消息管理组件 * * @author yangqisheng * @since 0.1.0 */ public class MessageComponent extends AbstractComponent { public MessageComponent(Weixin weixin) { super(weixin); } /** * 根据openid列表群发文本消息 * * @param openids 粉丝openid集合 * @param txtContent 文本消息内容 * @return 发送成功则返回群发消息Id,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public String massSendContent(String[] openids, String txtContent) throws WeixinException { JSONObject json = new JSONObject(); JSONObject text = new JSONObject(); text.put("content", txtContent); json.put("touser", openids); json.put("text", text); json.put("msgtype", "text"); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("群发文本消息返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { //返回群发消息id return jsonObj.getString("msg_id"); } } return null; } /** * 根据openid列表群发文本消息 * * @param openids 粉丝openid集合 * @param mediaId 图文消息素材Id * @return 发送成功则返回群发消息Id,否则返回null * @throws org.weixin4j.WeixinException 微信操作异常 */ public String massSendNews(String[] openids, String mediaId) throws WeixinException { JSONObject json = new JSONObject(); JSONObject media_id = new JSONObject(); media_id.put("media_id", mediaId); json.put("touser", openids); json.put("mpnews", media_id); json.put("msgtype", "mpnews"); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("/message/mass/send返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } else { //返回群发图文id return jsonObj.getString("msg_id"); } } return null; } /** * 发送客服文本消息 * * @param openid 粉丝openid * @param txtContent 文本消息内容 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void customSendContent(String openid, String txtContent) throws WeixinException { JSONObject json = new JSONObject(); JSONObject text = new JSONObject(); text.put("content", txtContent); json.put("touser", openid); json.put("text", text); json.put("msgtype", "text"); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("customSendContent返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 发送客服图文消息 * * @param openid 粉丝openid * @param articles 图文消息,一个图文消息支持1到10条图文 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void customSendNews(String openid, List<Articles> articles) throws WeixinException { JSONObject json = new JSONObject(); json.put("touser", openid); json.put("msgtype", "news"); JSONObject news = new JSONObject(); news.put("articles", articles); json.put("news", news); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("customSendNews返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 发送模板消息 * * @param openid 接收者 * @param templateId 模板消息ID * @param datas 模板数据 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void sendTemplateMessage(String openid, String templateId, List<TemplateData> datas) throws WeixinException { sendTemplateMessage(openid, templateId, datas, null, null); } /** * 发送模板消息(带跳转链接) * * @param openid 接收者 * @param templateId 模板消息ID * @param datas 模板数据 * @param miniprogram 跳小程序所需数据,不需跳小程序可不用传该数据 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void sendTemplateMessage(String openid, String templateId, List<TemplateData> datas, Miniprogram miniprogram) throws WeixinException { sendTemplateMessage(openid, templateId, datas, miniprogram, null); } /** * 发送模板消息(带跳转链接) * * @param openid 接收者 * @param templateId 模板消息ID * @param datas 模板数据 * @param url 模板跳转链接 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void sendTemplateMessage(String openid, String templateId, List<TemplateData> datas, String url) throws WeixinException { sendTemplateMessage(openid, templateId, datas, null, url); } /** * 发送模板消息(带跳转小程序或链接) * * <p> * 注:url和miniprogram都是非必填字段,若都不传则模板无跳转;若都传,会优先跳转至小程序。开发者可根据实际需要选择其中一种跳转方式即可。当用户的微信客户端版本不支持跳小程序时,将会跳转至url。</p> * * @param openid 接收者 * @param templateId 模板消息ID * @param datas 模板数据 * @param miniprogram 跳小程序所需数据,不需跳小程序可不用传该数据 * @param url 模板跳转链接 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void sendTemplateMessage(String openid, String templateId, List<TemplateData> datas, Miniprogram miniprogram, String url) throws WeixinException { //内部业务验证 if (openid == null || openid.equals("")) { throw new IllegalStateException("openid can not be null or empty"); } if (templateId == null || templateId.equals("")) { throw new IllegalStateException("templateId can not be null or empty"); } if (datas == null || datas.isEmpty()) { throw new IllegalStateException("datas can not be null or empty"); } JSONObject json = new JSONObject(); json.put("touser", openid); json.put("template_id", templateId); //添加模板跳转链接 if (url != null && !url.equals("")) { json.put("url", url); } //添加小程序 if (miniprogram != null) { JSONObject program = new JSONObject(); program.put("appid", miniprogram.getAppid()); program.put("pagepath", miniprogram.getPagepath()); json.put("miniprogram", program); } //添加模板数据 JSONObject data = new JSONObject(); for (TemplateData templateData : datas) { JSONObject dataContent = new JSONObject(); dataContent.put("value", templateData.getValue()); dataContent.put("color", templateData.getColor()); data.put(templateData.getKey(), dataContent); } json.put("data", data); //创建请求对象 HttpsClient http = new HttpsClient(); Response res = http.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + weixin.getToken().getAccess_token(), json); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("sendTemplateMessage返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null && !errcode.toString().equals("0")) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } } } /** * 发送模板消息 * * @param templateMessage 模板消息 * @throws org.weixin4j.WeixinException 微信操作异常 */ public void sendTemplateMessage(TemplateMessage templateMessage) throws WeixinException { sendTemplateMessage(templateMessage.getOpenid(), templateMessage.getTemplateId(), templateMessage.getData(), templateMessage.getMiniprogram(), templateMessage.getUrl()); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/factory/WeixinFactory.java
src/main/java/org/weixin4j/factory/WeixinFactory.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.factory; import org.weixin4j.Weixin; /** * 创建一个微信操作工厂类 * * @author yangqisheng * @since 1.0.0 */ public interface WeixinFactory { Weixin getWeixin(); }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/factory/defaults/DefaultWeixinFactory.java
src/main/java/org/weixin4j/factory/defaults/DefaultWeixinFactory.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.factory.defaults; import org.weixin4j.Weixin; import org.weixin4j.factory.WeixinFactory; /** * DefaultWeixinFactory * * @author yangqisheng * @since 1.0.0 */ public class DefaultWeixinFactory implements WeixinFactory { private Weixin weixin; public void setWeixin(Weixin weixin) { this.weixin = weixin; } @Override public Weixin getWeixin() { return weixin; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/http/HttpsClient.java
src/main/java/org/weixin4j/http/HttpsClient.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.http; import com.alibaba.fastjson.JSONException; import org.weixin4j.model.media.Attachment; import com.alibaba.fastjson.JSONObject; import java.io.BufferedInputStream; import org.weixin4j.Configuration; import org.weixin4j.WeixinException; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; /** * 请求微信平台及响应的客户端类 * * <p> * 每一次请求即对应一个<tt>HttpsClient</tt>, * 每次登陆产生一个<tt>OAuth</tt>用户连接,使用<tt>OAuthToken</tt> * 可以不用重复向微信平台发送登陆请求,在没有过期时间内,可继续请求。</p> * * @author yangqisheng * @since 0.0.1 */ public class HttpsClient implements java.io.Serializable { private static final int OK = 200; // OK: Success! private static final int CONNECTION_TIMEOUT = Configuration.getConnectionTimeout(); private static final int READ_TIMEOUT = Configuration.getReadTimeout(); private static final String DEFAULT_CHARSET = "UTF-8"; private static final String GET = "GET"; private static final String POST = "POST"; public HttpsClient() { } /** * Post JSON数据 * * 默认https方式 * * @param url 提交地址 * @param json JSON数据 * @return 输出流对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Response post(String url, JSONObject json) throws WeixinException { //将JSON数据转换为String字符串 String jsonString = json == null ? null : json.toString(); if (Configuration.isDebug()) { System.out.println("URL POST 数据:" + jsonString); } //提交数据 return httpsRequest(url, POST, jsonString, false, null, null); } /** * Get 请求 * * 默认https方式 * * @param url 请求地址 * @return 输出流对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Response get(String url) throws WeixinException { return httpsRequest(url, GET, null, false, null, null); } /** * Post XML格式数据 * * @param url 提交地址 * @param xml XML数据 * @return 输出流对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Response postXml(String url, String xml) throws WeixinException { return httpsRequest(url, POST, xml, false, null, null); } /** * Post XML格式数据 * * @param url 提交地址 * @param xml XML数据 * @param certPath 证书地址 * @param certSecret 证书密钥 * @return 输出流对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Response postXml(String url, String xml, String certPath, String certSecret) throws WeixinException { return httpsRequest(url, POST, xml, true, certPath, certSecret); } /** * 通过https协议请求url * * @param url 请求地址 * @param method 请求方式 * @param postData 请求数据 * @param needCert 是否需要证书 * @param certPath 商户证书路径 * @param certSecret 商户证书密钥 * @return * @throws WeixinException 微信操作异常 */ private Response httpsRequest(String url, String method, String postData, boolean needCert, String certPath, String certSecret) throws WeixinException { Response res = null; OutputStream output; HttpsURLConnection https; try { //创建https请求连接 https = getHttpsURLConnection(url); //判断https是否为空,如果为空返回null响应 if (https != null) { //设置Header信息,包括https证书 setHttpsHeader(https, method, needCert, certPath, certSecret); //判断是否需要提交数据 if (method.equals(POST) && null != postData) { //讲参数转换为字节提交 byte[] bytes = postData.getBytes(DEFAULT_CHARSET); //设置头信息 https.setRequestProperty("Content-Length", Integer.toString(bytes.length)); //开始连接 https.connect(); //获取返回信息 output = https.getOutputStream(); output.write(bytes); output.flush(); output.close(); } else { //开始连接 https.connect(); } //创建输出对象 res = new Response(https); //获取响应代码 if (res.getStatus() == OK) { return res; } } } catch (NoSuchAlgorithmException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (KeyManagementException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (NoSuchProviderException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (IOException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (KeyStoreException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (CertificateException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (UnrecoverableKeyException ex) { throw new WeixinException(ex.getMessage(), ex); } return res; } /** * 获取https请求连接 * * @param url 连接地址 * @return https连接对象 * @throws IOException IO异常 */ private HttpsURLConnection getHttpsURLConnection(String url) throws IOException { URL urlGet = new URL(url); //创建https请求 HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) urlGet.openConnection(); return httpsUrlConnection; } private void setHttpsHeader(HttpsURLConnection httpsUrlConnection, String method, boolean needCert, String certPath, String certSecret) throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException, IOException, KeyStoreException, CertificateException, UnrecoverableKeyException { //不需要维修证书,则使用默认证书 if (!needCert) { //创建https请求证书 TrustManager[] tm = {new MyX509TrustManager()}; //创建证书上下文对象 SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); //初始化证书信息 sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); //设置ssl证书 httpsUrlConnection.setSSLSocketFactory(ssf); } else { //指定读取证书格式为PKCS12 KeyStore keyStore = KeyStore.getInstance("PKCS12"); //读取本机存放的PKCS12证书文件 FileInputStream instream = new FileInputStream(new File(certPath)); try { //指定PKCS12的密码 keyStore.load(instream, certSecret.toCharArray()); } finally { instream.close(); } KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keyStore, certSecret.toCharArray()); //创建管理jks密钥库的x509密钥管理器,用来管理密钥,需要key的密码 SSLContext sslContext = SSLContext.getInstance("TLSv1"); // 构造SSL环境,指定SSL版本为3.0,也可以使用TLSv1,但是SSLv3更加常用。 sslContext.init(kmf.getKeyManagers(), null, null); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); //设置ssl证书 httpsUrlConnection.setSSLSocketFactory(ssf); } //设置header信息 httpsUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //设置User-Agent信息 httpsUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); //设置可接受信息 httpsUrlConnection.setDoOutput(true); //设置可输入信息 httpsUrlConnection.setDoInput(true); //设置请求方式 httpsUrlConnection.setRequestMethod(method); //设置连接超时时间 if (CONNECTION_TIMEOUT > 0) { httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT); } else { //默认10秒超时 httpsUrlConnection.setConnectTimeout(10000); } //设置请求超时 if (READ_TIMEOUT > 0) { httpsUrlConnection.setReadTimeout(READ_TIMEOUT); } else { //默认10秒超时 httpsUrlConnection.setReadTimeout(10000); } //设置编码 httpsUrlConnection.setRequestProperty("Charsert", "UTF-8"); } /** * 上传文件 * * @param url 上传地址 * @param file 上传文件对象 * @return 服务器上传响应结果 * @throws org.weixin4j.WeixinException 微信操作异常 */ public String uploadHttps(String url, File file) throws WeixinException { HttpsURLConnection https = null; StringBuffer bufferRes = new StringBuffer(); try { // 定义数据分隔线 String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; //创建https请求连接 https = getHttpsURLConnection(url); //设置header和ssl证书 setHttpsHeader(https, POST, false, null, null); //不缓存 https.setUseCaches(false); //保持连接 https.setRequestProperty("connection", "Keep-Alive"); //设置文档类型 https.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); //定义输出流 OutputStream out = null; //定义输入流 DataInputStream dataInputStream; try { out = new DataOutputStream(https.getOutputStream()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线 StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filename=\"").append(file.getName()).append("\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); //读取文件流 dataInputStream = new DataInputStream(new FileInputStream(file)); int bytes; byte[] bufferOut = new byte[1024]; while ((bytes = dataInputStream.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个 dataInputStream.close(); out.write(end_data); out.flush(); } finally { if (out != null) { out.close(); } } // 定义BufferedReader输入流来读取URL的响应 InputStream ins = null; try { ins = https.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(ins, "UTF-8")); String valueString; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } } finally { if (ins != null) { ins.close(); } } } catch (IOException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (NoSuchAlgorithmException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (KeyManagementException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (NoSuchProviderException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (KeyStoreException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (CertificateException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (UnrecoverableKeyException ex) { throw new WeixinException(ex.getMessage(), ex); } finally { if (https != null) { // 关闭连接 https.disconnect(); } } return bufferRes.toString(); } /** * 下载附件 * * @param url 附件地址 * @return 附件对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Attachment downloadHttps(String url) throws WeixinException { //定义下载附件对象 Attachment attachment = null; HttpsURLConnection https; try { //创建https请求连接 https = getHttpsURLConnection(url); //设置header和ssl证书 setHttpsHeader(https, POST, false, null, null); //不缓存 https.setUseCaches(false); //保持连接 https.setRequestProperty("connection", "Keep-Alive"); //获取输入流 InputStream in = https.getInputStream(); //初始化返回附件对象 attachment = new Attachment(); String contentType = https.getContentType(); //出现错误时,返回错误消息 if (contentType.contains("text/plain")) { // 定义BufferedReader输入流来读取URL的响应 BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8")); String valueString; StringBuilder bufferRes = new StringBuilder(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } String textString = bufferRes.toString(); if (textString.contains("video_url")) { try { JSONObject result = JSONObject.parseObject(textString); if (result.containsKey("errcode") && result.getIntValue("errcode") != 0) { attachment.setError(result.getString("errmsg")); } else if (result.containsKey("video_url")) { //发起get请求获取视频流 HttpClient httpClient = new HttpClient(); return httpClient.download(result.getString("video_url")); } else { //未知格式 attachment.setError(textString); } } catch (JSONException ex) { attachment.setError(textString); } } else { attachment.setError(textString); } } else if (contentType.contains("application/json")) { // 定义BufferedReader输入流来读取URL的响应 BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8")); String valueString; StringBuilder bufferRes = new StringBuilder(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } String jsonString = bufferRes.toString(); JSONObject result = JSONObject.parseObject(jsonString); if (result.containsKey("errcode") && result.getIntValue("errcode") != 0) { attachment.setError(result.getString("errmsg")); } else if (result.containsKey("video_url")) { //发起get请求获取视频流 HttpClient httpClient = new HttpClient(); return httpClient.download(result.getString("video_url")); } else { //未知格式 attachment.setError(jsonString); } } else { BufferedInputStream bis = new BufferedInputStream(in); String ds = https.getHeaderField("Content-disposition"); String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1); String relName = fullName.substring(0, fullName.lastIndexOf(".")); String suffix = fullName.substring(relName.length() + 1); attachment.setFullName(fullName); attachment.setFileName(relName); attachment.setSuffix(suffix); attachment.setContentLength(https.getHeaderField("Content-Length")); attachment.setContentType(https.getHeaderField("Content-Type")); attachment.setFileStream(bis); } } catch (IOException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (NoSuchAlgorithmException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (KeyManagementException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (NoSuchProviderException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (KeyStoreException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (CertificateException ex) { throw new WeixinException(ex.getMessage(), ex); } catch (UnrecoverableKeyException ex) { throw new WeixinException(ex.getMessage(), ex); } finally { } return attachment; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/http/HttpClient.java
src/main/java/org/weixin4j/http/HttpClient.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.http; import com.alibaba.fastjson.JSONObject; import org.weixin4j.model.media.Attachment; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import org.weixin4j.Configuration; import org.weixin4j.WeixinException; /** * HttpClient业务 * * @author yangqisheng * @since 0.0.1 */ public class HttpClient implements java.io.Serializable { private static final int OK = 200; // OK: Success! private static final int ConnectionTimeout = Configuration.getConnectionTimeout(); private static final int ReadTimeout = Configuration.getReadTimeout(); private static final String DEFAULT_CHARSET = "UTF-8"; private static final String _GET = "GET"; private static final String _POST = "POST"; /** * Get 请求 * * @param url 请求地址 * @return 输出流对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public Response get(String url) throws WeixinException { return httpRequest(url, _GET, null); } /** * 上传文件 * * @param url 上传地址 * @param file 上传文件对象 * @return 服务器上传响应结果 * @throws IOException IO异常 * @throws NoSuchAlgorithmException 算法异常 * @throws NoSuchProviderException 私钥异常 * @throws KeyManagementException 密钥异常 */ public String upload(String url, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { HttpURLConnection http = null; StringBuffer bufferRes = new StringBuffer(); try { // 定义数据分隔线 String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; //创建https请求连接 http = getHttpURLConnection(url); //设置header和ssl证书 setHttpHeader(http, _POST); //不缓存 http.setUseCaches(false); //保持连接 http.setRequestProperty("connection", "Keep-Alive"); //设置文档类型 http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); //定义输出流 OutputStream out = null; //定义输入流 DataInputStream dataInputStream; try { out = new DataOutputStream(http.getOutputStream()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线 StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filename=\"").append(file.getName()).append("\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); //读取文件流 dataInputStream = new DataInputStream(new FileInputStream(file)); int bytes; byte[] bufferOut = new byte[1024]; while ((bytes = dataInputStream.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个 dataInputStream.close(); out.write(end_data); out.flush(); } finally { if (out != null) { out.close(); } } // 定义BufferedReader输入流来读取URL的响应 InputStream ins = null; try { ins = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(ins, "UTF-8")); String valueString; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } } finally { if (ins != null) { ins.close(); } } } finally { if (http != null) { // 关闭连接 http.disconnect(); } } return bufferRes.toString(); } /** * 下载附件 * * @param url 附件地址 * @return 附件对象 * @throws IOException IO异常 */ public Attachment download(String url) throws IOException { Attachment attachment = new Attachment(); URL _url = new URL(url); HttpURLConnection http = (HttpURLConnection) _url.openConnection(); //设置头 setHttpHeader(http, "GET"); if (http.getContentType().equalsIgnoreCase("text/plain")) { // 定义BufferedReader输入流来读取URL的响应 InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8")); String valueString; StringBuilder bufferRes = new StringBuilder(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); attachment.setError(bufferRes.toString()); } else if (http.getContentType().contains("application/json")) { // 定义BufferedReader输入流来读取URL的响应 InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8")); String valueString; StringBuilder bufferRes = new StringBuilder(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); String jsonString = bufferRes.toString(); JSONObject result = JSONObject.parseObject(jsonString); if (result.containsKey("errcode") && result.getIntValue("errcode") != 0) { attachment.setError(result.getString("errmsg")); } else { //未知格式 attachment.setError(jsonString); } } else { BufferedInputStream bis = new BufferedInputStream(http.getInputStream()); String ds = http.getHeaderField("Content-disposition"); String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1); String relName = fullName.substring(0, fullName.lastIndexOf(".")); String suffix = fullName.substring(relName.length() + 1); attachment.setFullName(fullName); attachment.setFileName(relName); attachment.setSuffix(suffix); attachment.setContentLength(http.getHeaderField("Content-Length")); attachment.setContentType(http.getHeaderField("Content-Type")); attachment.setFileStream(bis); } return attachment; } /** * 获取http请求连接 * * @param url 连接地址 * @return http连接对象 * @throws IOException IO异常 */ private HttpURLConnection getHttpURLConnection(String url) throws IOException { URL urlGet = new URL(url); HttpURLConnection con = (HttpURLConnection) urlGet.openConnection(); return con; } /** * 通过http协议请求url * * @param url 提交地址 * @param method 提交方式 * @param postData 提交数据 * @return 响应流 * @throws org.weixin4j.WeixinException 微信操作异常 */ private Response httpRequest(String url, String method, String postData) throws WeixinException { Response res = null; OutputStream output; HttpURLConnection http; try { //创建https请求连接 http = getHttpURLConnection(url); //判断https是否为空,如果为空返回null响应 if (http != null) { //设置Header信息 setHttpHeader(http, method); //判断是否需要提交数据 if (method.equals(_POST) && null != postData) { //讲参数转换为字节提交 byte[] bytes = postData.getBytes(DEFAULT_CHARSET); //设置头信息 http.setRequestProperty("Content-Length", Integer.toString(bytes.length)); //开始连接 http.connect(); //获取返回信息 output = http.getOutputStream(); output.write(bytes); output.flush(); output.close(); } else { //开始连接 http.connect(); } //创建输出对象 res = new Response(http); //获取响应代码 if (res.getStatus() == OK) { return res; } } } catch (IOException ex) { throw new WeixinException(ex.getMessage(), ex); } return res; } private void setHttpHeader(HttpURLConnection httpUrlConnection, String method) throws IOException { //设置header信息 httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //设置User-Agent信息 httpUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); //设置可接受信息 httpUrlConnection.setDoOutput(true); //设置可输入信息 httpUrlConnection.setDoInput(true); //设置请求方式 httpUrlConnection.setRequestMethod(method); //设置连接超时时间 if (ConnectionTimeout > 0) { httpUrlConnection.setConnectTimeout(ConnectionTimeout); } else { //默认10秒超时 httpUrlConnection.setConnectTimeout(10000); } //设置请求超时 if (ReadTimeout > 0) { httpUrlConnection.setReadTimeout(ReadTimeout); } else { //默认10秒超时 httpUrlConnection.setReadTimeout(10000); } //设置编码 httpUrlConnection.setRequestProperty("Charsert", "UTF-8"); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/http/MyX509TrustManager.java
src/main/java/org/weixin4j/http/MyX509TrustManager.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.http; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * Https证书管理类 * * @author yangqisheng * @since 0.0.1 */ public class MyX509TrustManager implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/src/main/java/org/weixin4j/http/Response.java
src/main/java/org/weixin4j/http/Response.java
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * 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 org.weixin4j.http; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.weixin4j.WeixinException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import javax.net.ssl.HttpsURLConnection; /** * <p> * Title: https的输出流</p> * * <p> * Description: </p> * * @author yangqisheng * @since 0.0.1 */ public class Response { private HttpsURLConnection https; private HttpURLConnection http; private int status; private InputStream is; private String responseAsString = null; private boolean streamConsumed = false; public Response() { } public Response(HttpsURLConnection https) throws IOException { this.https = https; this.status = https.getResponseCode(); if (null == (is = https.getErrorStream())) { is = https.getInputStream(); } } public Response(HttpURLConnection http) throws IOException { this.http = http; this.status = http.getResponseCode(); if (null == (is = http.getErrorStream())) { is = http.getInputStream(); } } /** * 转换为输出流 * * @return 输出流 */ public InputStream asStream() { if (streamConsumed) { throw new IllegalStateException("Stream has already been consumed."); } return is; } /** * 将输出流转换为String字符串 * * @return 输出内容 * @throws org.weixin4j.WeixinException 微信操作异常 */ public String asString() throws WeixinException { if (null == responseAsString) { BufferedReader br; try { InputStream stream = asStream(); if (null == stream) { return null; } br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); StringBuilder buf = new StringBuilder(); String line; while (null != (line = br.readLine())) { buf.append(line).append("\n"); } this.responseAsString = buf.toString(); stream.close(); //输出流读取完毕,关闭连接 if (https != null) { https.disconnect(); } //输出流读取完毕,关闭连接 if (http != null) { http.disconnect(); } streamConsumed = true; } catch (NullPointerException npe) { // don't remember in which case npe can be thrown throw new WeixinException(npe.getMessage(), npe); } catch (IOException ioe) { throw new WeixinException(ioe.getMessage(), ioe); } } return responseAsString; } /** * 将输出流转换为JSON对象 * * @return JSONObject对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public JSONObject asJSONObject() throws WeixinException { return JSONObject.parseObject(asString()); } /** * 将输出流转换为JSON对象 * * @return JSONArray对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public JSONArray asJSONArray() throws WeixinException { return JSONArray.parseArray(asString()); } /** * 获取响应状态 * * @return 响应状态 */ public int getStatus() { return status; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/example/weixin4j-example/src/main/java/com/ansitech/weixin4j/example/Demo.java
example/weixin4j-example/src/main/java/com/ansitech/weixin4j/example/Demo.java
package com.ansitech.weixin4j.example; import java.util.ArrayList; import java.util.List; import org.weixin4j.Configuration; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.component.MenuComponent; import org.weixin4j.model.menu.ClickButton; import org.weixin4j.model.menu.MiniprogramButton; import org.weixin4j.model.menu.SingleButton; import org.weixin4j.model.menu.ViewButton; /** * 开始开发,weixin4j使用入门 * * 本示例介绍了weixin4j开发中的入口,对于独立项目中仅用来做一些快速上手的接口 * * 进行调用,快速入门使用,对于需要微信网页开发请大家参考weixin4j-web-demo * * @author 杨启盛<qsyang@ansitech.com> */ public class Demo { /** * 本示例直接采用main方法运行,做到开箱即用 * * Weixin对象为调用入口,里面包含了几乎常用的接口,并以组件的方式展示, * * 本示例展示了自定义菜单的创建,以供初学者参考 * * @param args */ public static void main(String[] args) { //系统会直接从weixin4j.properties中读取配置 //weixin4j.properties可以放在classes下,即项目的src目录下 //对于maven项目,则放在resources目录下 //但是优先以系统设置的属性为准,例如: System.setProperty("weixin4j.debug", "false"); //打印调试开关,如果打开调试开关,则会向控制台打印方法调用执行日志 System.out.println(Configuration.isDebug()); //1.初始化weixin对象 Weixin weixin = new Weixin(); //2.打印开发者appid System.out.println(weixin.getAppId()); //3.下面为大家演示利用菜单组件来创建公众号自定义菜单 //组件命名以微信的接口api请求为名 //例如自定义菜单接口请求地址 // https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN //则是menu/create,则我们取menu为组件名,其他组件以此类推 //3.1获取菜单组件 MenuComponent menuComponet = weixin.menu(); //调用组件创建方法 //menuComponet.create(menu); //组件创建需要一个Menu对象,我们也可以看到这个对象在org.weixin4j.model目录下 //model目录下是我们所有开发中用到的对象,也是以组件分的包名 //例如自定义菜单组件,就是menu,所有相关对象则=在org.weixin4j.model.menu下 org.weixin4j.model.menu.Menu menu = new org.weixin4j.model.menu.Menu(); //关于menu对象,有2个构造函数,一个带参,一个不带参 //带参的构造函数是一个json对象,需要的格式为{menu:{...}} //这个menu是必须包含的对象,对象内是一个按钮对象集合,以官方网站示例为例: //{ // "button":[ // { // "type":"click", // "name":"今日歌曲", // "key":"V1001_TODAY_MUSIC" // }, // { // "name":"菜单", // "sub_button":[ // { // "type":"view", // "name":"搜索", // "url":"http://www.soso.com/" // }, // { // "type":"miniprogram", // "name":"wxa", // "url":"http://mp.weixin.qq.com", // "appid":"wx286b93c14bbf93aa", // "pagepath":"pages/lunar/index" // }, // { // "type":"click", // "name":"赞一下我们", // "key":"V1001_GOOD" // }] // }] // } //下面是json创建自定义菜单的案例 //String json = "{\"menu\":\" {" // + " \"button\":[" // + " { " // + " \"type\":\"click\"," // + " \"name\":\"今日歌曲\"," // + " \"key\":\"V1001_TODAY_MUSIC\"" // + " }," // + " {" // + " \"name\":\"菜单\"," // + " \"sub_button\":[" // + " { " // + " \"type\":\"view\"," // + " \"name\":\"搜索\"," // + " \"url\":\"http://www.soso.com/\"" // + " }," // + " {" // + " \"type\":\"miniprogram\"," // + " \"name\":\"wxa\"," // + " \"url\":\"http://mp.weixin.qq.com\"," // + " \"appid\":\"wx286b93c14bbf93aa\"," // + " \"pagepath\":\"pages/lunar/index\"" // + " }," // + " {" // + " \"type\":\"click\"," // + " \"name\":\"赞一下我们\"," // + " \"key\":\"V1001_GOOD\"" // + " }]" // + " }]" // + " }\"}"; //org.weixin4j.model.menu.Menu menu = new org.weixin4j.model.menu.Menu(json); //接下面我们演示用对象的方式创建自定义菜单 List<SingleButton> buttons = new ArrayList<SingleButton>(); //创建菜单1 click button ClickButton button1 = new ClickButton("今日歌曲", "V1001_TODAY_MUSIC"); //添加一级菜单1 buttons.add(button1); //创建菜单2 可以包含二级子菜单 SingleButton button2 = new SingleButton("菜单"); //创建2级子菜单1,打开页面 ViewButton button2_1 = new ViewButton("搜索", "http://www.soso.com/"); button2.getSubButton().add(button2_1); //创建2级子菜单2,打开小程序 MiniprogramButton button2_2 = new MiniprogramButton("wxa"); button2_2.setAppid("wx286b93c14bbf93aa"); button2_2.setPagepath("pages/lunar/index"); button2_2.setUrl("http://mp.weixin.qq.com"); button2.getSubButton().add(button2_2); //创建2级子菜单3,点击事件 ClickButton button2_3 = new ClickButton("赞一下我们", "V1001_GOOD"); button2.getSubButton().add(button2_3); //添加一级菜单2 buttons.add(button2); //设置自定义菜单 menu.setButton(buttons); System.out.println(menu.toJSONObject().toJSONString()); //try { // // //调用微信自定义菜单组件,创建自定义菜单 // //menuComponet.create(menu); //} catch (WeixinException ex) { // //打印创建异常日志 // ex.printStackTrace(); //} } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/example/weixin4j-example-web/src/main/java/com/ansitech/weixin4j/example/Application.java
example/weixin4j-example-web/src/main/java/com/ansitech/weixin4j/example/Application.java
package com.ansitech.weixin4j.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * 程序入口 * * @author yangqisheng */ @SpringBootApplication @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/example/weixin4j-example-web/src/main/java/com/ansitech/weixin4j/example/controller/WeixinJieruController.java
example/weixin4j-example-web/src/main/java/com/ansitech/weixin4j/example/controller/WeixinJieruController.java
package com.ansitech.weixin4j.example.controller; import java.io.IOException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.weixin4j.WeixinException; import org.weixin4j.spi.HandlerFactory; import org.weixin4j.spi.IMessageHandler; import org.weixin4j.util.TokenUtil; /** * 微信开发者接入 * * @author yangqisheng */ @Controller @RequestMapping("/weixin/jieru") public class WeixinJieruController { //开发者接入验证 @RequestMapping(method = RequestMethod.GET) public void get(HttpServletRequest request, HttpServletResponse response) throws IOException { //消息来源可靠性验证 String signature = request.getParameter("signature");// 微信加密签名 String timestamp = request.getParameter("timestamp");// 时间戳 String nonce = request.getParameter("nonce"); // 随机数 //Token为weixin4j.properties中配置的Token String token = TokenUtil.get(); //1.验证消息真实性 //http://mp.weixin.qq.com/wiki/index.php?title=验证消息真实性 //成为开发者验证 String echostr = request.getParameter("echostr"); //确认此次GET请求来自微信服务器,原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败 if (TokenUtil.checkSignature(token, signature, timestamp, nonce)) { response.getWriter().write(echostr); } } //接收微信消息 @RequestMapping(method = RequestMethod.POST) public void post(HttpServletRequest request, HttpServletResponse response) throws IOException { //消息来源可靠性验证 String signature = request.getParameter("signature");// 微信加密签名 String timestamp = request.getParameter("timestamp");// 时间戳 String nonce = request.getParameter("nonce"); // 随机数 //Token为weixin4j.properties中配置的Token String token = TokenUtil.get(); //确认此次GET请求来自微信服务器,原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败 if (!TokenUtil.checkSignature(token, signature, timestamp, nonce)) { //消息不可靠,直接返回 response.getWriter().write(""); return; } //用户每次向公众号发送消息、或者产生自定义菜单点击事件时,响应URL将得到推送 try { response.setCharacterEncoding("UTF-8"); response.setContentType("text/xml"); //获取POST流 ServletInputStream in = request.getInputStream(); //非注解方式,依然采用消息处理工厂模式调用 IMessageHandler messageHandler = HandlerFactory.getMessageHandler(); //处理输入消息,返回结果 String xml = messageHandler.invoke(in); //返回结果 response.getWriter().write(xml); } catch (IOException | WeixinException ex) { response.getWriter().write(""); } } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/example/weixin4j-example-web/src/main/java/com/ansitech/weixin4j/example/handler/AtsEventMessageHandler.java
example/weixin4j-example-web/src/main/java/com/ansitech/weixin4j/example/handler/AtsEventMessageHandler.java
package com.ansitech.weixin4j.example.handler; import org.weixin4j.model.message.OutputMessage; import org.weixin4j.model.message.event.ClickEventMessage; import org.weixin4j.model.message.event.LocationEventMessage; import org.weixin4j.model.message.event.LocationSelectEventMessage; import org.weixin4j.model.message.event.PicPhotoOrAlbumEventMessage; import org.weixin4j.model.message.event.PicSysPhotoEventMessage; import org.weixin4j.model.message.event.PicWeixinEventMessage; import org.weixin4j.model.message.event.QrsceneScanEventMessage; import org.weixin4j.model.message.event.QrsceneSubscribeEventMessage; import org.weixin4j.model.message.event.ScanCodePushEventMessage; import org.weixin4j.model.message.event.ScanCodeWaitMsgEventMessage; import org.weixin4j.model.message.event.SubscribeEventMessage; import org.weixin4j.model.message.event.UnSubscribeEventMessage; import org.weixin4j.model.message.event.ViewEventMessage; import org.weixin4j.model.message.output.TextOutputMessage; import org.weixin4j.spi.IEventMessageHandler; /** * 自定义事件消息处理器 * * @author yangqisheng */ public class AtsEventMessageHandler implements IEventMessageHandler { @Override public OutputMessage subscribe(SubscribeEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("感谢您的关注!"); return out; } @Override public OutputMessage unSubscribe(UnSubscribeEventMessage msg) { //取消关注 return null; } @Override public OutputMessage qrsceneSubscribe(QrsceneSubscribeEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("感谢您的关注!,来源:" + msg.getEventKey()); return out; } @Override public OutputMessage qrsceneScan(QrsceneScanEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("你的消息已经收到!"); return out; } @Override public OutputMessage location(LocationEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("你的消息已经收到!"); return out; } @Override public OutputMessage click(ClickEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("点击了菜单!"); return out; } @Override public OutputMessage view(ViewEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("点击了链接!"); return out; } @Override public OutputMessage scanCodePush(ScanCodePushEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("扫码!"); return out; } @Override public OutputMessage scanCodeWaitMsg(ScanCodeWaitMsgEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("扫码等待中!"); return out; } @Override public OutputMessage picSysPhoto(PicSysPhotoEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("发起拍照!"); return out; } @Override public OutputMessage picPhotoOrAlbum(PicPhotoOrAlbumEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("选择相册!"); return out; } @Override public OutputMessage picWeixin(PicWeixinEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("上次图片!"); return out; } @Override public OutputMessage locationSelect(LocationSelectEventMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("选择地理位置!"); return out; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
ansitech/weixin4j
https://github.com/ansitech/weixin4j/blob/f5e7a60e0c377f7420866b229a9ac79e687d5ac5/example/weixin4j-example-web/src/main/java/com/ansitech/weixin4j/example/handler/AtsNormalMessageHandler.java
example/weixin4j-example-web/src/main/java/com/ansitech/weixin4j/example/handler/AtsNormalMessageHandler.java
package com.ansitech.weixin4j.example.handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.weixin4j.model.message.OutputMessage; import org.weixin4j.model.message.normal.ImageInputMessage; import org.weixin4j.model.message.normal.LinkInputMessage; import org.weixin4j.model.message.normal.LocationInputMessage; import org.weixin4j.model.message.normal.ShortVideoInputMessage; import org.weixin4j.model.message.normal.TextInputMessage; import org.weixin4j.model.message.normal.VideoInputMessage; import org.weixin4j.model.message.normal.VoiceInputMessage; import org.weixin4j.model.message.output.TextOutputMessage; import org.weixin4j.spi.INormalMessageHandler; /** * 自定义普通消息处理器 * * @author yangqisheng */ public class AtsNormalMessageHandler implements INormalMessageHandler { protected final Logger LOG = LoggerFactory.getLogger(AtsNormalMessageHandler.class); @Override public OutputMessage textTypeMsg(TextInputMessage msg) { LOG.debug("文本消息:" + msg.getContent()); TextOutputMessage out = new TextOutputMessage(); out.setContent("您发的消息是:" + msg.getContent()); return out; } @Override public OutputMessage imageTypeMsg(ImageInputMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("你的消息已经收到!"); return out; } @Override public OutputMessage voiceTypeMsg(VoiceInputMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("你的消息已经收到!"); return out; } @Override public OutputMessage videoTypeMsg(VideoInputMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("你的消息已经收到!"); return out; } @Override public OutputMessage shortvideoTypeMsg(ShortVideoInputMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("你的消息已经收到!"); return out; } @Override public OutputMessage locationTypeMsg(LocationInputMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("你的消息已经收到!"); return out; } @Override public OutputMessage linkTypeMsg(LinkInputMessage msg) { TextOutputMessage out = new TextOutputMessage(); out.setContent("你的消息已经收到!"); return out; } }
java
Apache-2.0
f5e7a60e0c377f7420866b229a9ac79e687d5ac5
2026-01-05T02:42:41.143783Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/RedissonApplication.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/RedissonApplication.java
package redisson; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @EnableAsync @EnableScheduling @SpringBootApplication @MapperScan("redisson.dao") public class RedissonApplication { public static void main(String[] args) { SpringApplication.run(RedissonApplication.class, args); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/controller/backstage/TransactionRecordController.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/controller/backstage/TransactionRecordController.java
package redisson.controller.backstage; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import redisson.config.tingyu.operation.RedissonObject; import java.util.Random; /** * @author ransong * @version 1.0 * @date 2019/11/15 0015 17:02 */ @RestController @RequestMapping("/backstage/transaction") public class TransactionRecordController { private final static Logger logger = LoggerFactory.getLogger(TransactionRecordController.class); @Autowired RedissonClient redissonClient; @Autowired RedissonObject redissonObject; // @Autowired // RedisCache redisCache; /** * * @return */ @RequestMapping(value = "/redisTest", method = RequestMethod.GET) public int transactionRecordList() { String lockKey = "com_lock"; String lockKey1 = "com_locka"; RLock rLock = redissonClient.getLock(lockKey1); int uuid = new Random().nextInt(10000); Boolean isDelBetKeyIncr = true; String betKeyIncr = "Test" + uuid; String allvalue = "0"; rLock.lock(); try { int stock = Integer.parseInt(redissonObject.getValue(lockKey)); // Long incr = redisCache.incrementForValue(betKeyIncr, 1); // Long value = redisCache.incrementForValue(allvalue, 1); // if (incr == null || incr != 1) { // isDelBetKeyIncr = false; // logger.info("请稍后再试"); // return 1; // } ;//Integer.parseInt(redisCache.getForValue(lockKey)); if (stock > 0) { int realStock = stock -1; redissonObject.setValue(lockKey,String.valueOf(realStock)); // redisCache.putForValue(lockKey,String.valueOf(realStock)); logger.info("扣减成功,剩余库存:" + realStock); } else { logger.info("请稍后再试"); } } catch (Exception e) { } finally { rLock.unlock(); // if (isDelBetKeyIncr) { // redisCache.deleteForValue(betKeyIncr); // logger.info(redisCache.getForValue(allvalue)); // } } return 2; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/dao/EntrustMapper.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/dao/EntrustMapper.java
package redisson.dao; import redisson.bean.po.Entrust; import java.util.List; public interface EntrustMapper { int deleteByPrimaryKey(String id); int insert(Entrust record); int insertSelective(Entrust record); Entrust selectByPrimaryKey(String id); int updateByPrimaryKeySelective(Entrust record); int updateByPrimaryKey(Entrust record); }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/dao/OrderMapper.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/dao/OrderMapper.java
package redisson.dao; import redisson.bean.po.Order; import java.util.List; public interface OrderMapper { int deleteByPrimaryKey(String id); int insert(Order record); int insertSelective(Order record); Order selectByPrimaryKey(String id); int updateByPrimaryKeySelective(Order record); int updateByPrimaryKey(Order record); }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/util/RSACoder.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/util/RSACoder.java
package redisson.util; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; public class RSACoder { // 非对称密钥算法 public static final String KEY_ALGORITHM = "RSA"; /** * 密钥长度,DH算法的默认密钥长度是1024 密钥长度必须是64的倍数,在512到65536位之间 */ private static final int KEY_SIZE = 1024; // 公钥 private static final String PUBLIC_KEY = "RSAPublicKey"; // 私钥 private static final String PRIVATE_KEY = "RSAPrivateKey"; private static final int MAX_ENCRYPT_BLOCK = 117; private static final int MAX_DECRYPT_BLOCK = 128; /** * 初始化密钥对 * * @return Map 甲方密钥的Map */ public static Map<String, Object> initKey() throws Exception { // 实例化密钥生成器 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); // 初始化密钥生成器 keyPairGenerator.initialize(KEY_SIZE); // 生成密钥对 KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 甲方公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 甲方私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 将密钥存储在map中 Map<String, Object> keyMap = new HashMap<String, Object>(); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** * 私钥加密 * * @param data 待加密数据 * @param key 密钥 * @return byte[] 加密数据 */ public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception { // 取得私钥 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // 生成私钥 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); // 数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(data); } /** * 公钥加密 * * @param data 待加密数据 * @param key 密钥 * @return byte[] 加密数据 */ public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception { // 实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // 初始化公钥 // 密钥材料转换 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key); // 产生公钥 PublicKey pubKey = keyFactory.generatePublic(x509KeySpec); // 数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pubKey); // 对数据分段解密 ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] cache; int inputLen = data.length; int offSet = 0; int i = 0; while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** * 私钥解密 * * @param data 待解密数据 * @param key 密钥 * @return byte[] 解密数据 */ public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception { // 取得私钥 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // 生成私钥 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); // 数据解密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); // 对数据分段解密 ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] cache; int inputLen = data.length; int offSet = 0; int i = 0; while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** * 取得私钥 * * @param keyMap 密钥map * @return byte[] 私钥 */ public static byte[] getPrivateKey(Map<String, Object> keyMap) { Key key = (Key) keyMap.get(PRIVATE_KEY); return key.getEncoded(); } /** * 取得公钥 * * @param keyMap 密钥map * @return byte[] 公钥 */ public static byte[] getPublicKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return key.getEncoded(); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // 初始化密钥 // 生成密钥对 Map<String, Object> keyMap = RSACoder.initKey(); // 公钥 byte[] publicKey = RSACoder.getPublicKey(keyMap); // 私钥 byte[] privateKey = RSACoder.getPrivateKey(keyMap); System.out.println("公钥:/n" + Base64.encodeBase64String(publicKey)); System.out.println("私钥:/n" + Base64.encodeBase64String(privateKey)); // // System.out.println("================密钥对构造完毕,甲方将公钥公布给乙方,开始进行加密数据的传输============="); // String str = "RSA密码交换算法"; // System.out.println("/n===========甲方向乙方发送加密数据=============="); // System.out.println("原文:" + str); // //甲方进行数据的加密 // byte[] code1 = RSACoder.encryptByPrivateKey(str.getBytes(), privateKey); // System.out.println("加密后的数据:" + Base64.encodeBase64String(code1)); // System.out.println("===========乙方使用甲方提供的公钥对数据进行解密=============="); // //乙方进行数据的解密 // byte[] decode1 = RSACoder.decryptByPublicKey(code1, publicKey); // System.out.println("乙方解密后的数据:" + new String(decode1) + "/n/n"); // // System.out.println("===========反向进行操作,乙方向甲方发送数据==============/n/n"); // // str = "乙方向甲方发送数据RSA算法"; // // System.out.println("原文:" + str); // // //乙方使用公钥对数据进行加密 // byte[] code2 = RSACoder.encryptByPublicKey(str.getBytes(), publicKey); // System.out.println("===========乙方使用公钥对数据进行加密=============="); // System.out.println("加密后的数据:" + Base64.encodeBase64String(code2)); // // System.out.println("=============乙方将数据传送给甲方======================"); // System.out.println("===========甲方使用私钥对数据进行解密=============="); // // //甲方使用私钥对数据进行解密 // byte[] decode2 = RSACoder.decryptByPrivateKey(code2, privateKey); // // System.out.println("甲方解密后的数据:" + new String(decode2)); // String str = "X9z6MWFERDNhXZJtn16CeKI7RVGSq5wcHKoGt7Dzofq+WzcTn5hsXF9d3gBGLAt2qE/YxiFV3ca4MH0QLzo5UQ=="; // String privateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqXg9cInSteK2x5Ja2EQFuA0y/md0U49VrNAHKvUUnWC/VK+J4vYuu7wYq9U+VBM6el3lm5V9bnzQj7zX2ytEyQIDAQABAkAP2prM02ft8hatVui+wKZUUI/Lsvvz8T3Pm+p/v0u9aS7RdZ360hyYeUCFJnpYoIeDfkCzIVyDF/MJ7jr+vCGBAiEA/73pUSbvPh+yHUxM9OqUyJEHMKij5UjmoN70fSymKLECIQCppAjCwh6Y+6oSJ5Sq0niimM2TR0lLdzLNx7HkpEjjmQIgOke2HvdHeBnTBlg4BWxcAaUDRXR4/Sxy2mBUyR3es9ECICUs92aG1+G6tQiJeAD/YsRvLA3sf1l0Y8PI0WlDv11xAiEAnlk0O7wbmaA8o9tsUNJ0uP4SkjJBRABduJbNafH9WzY="; // // byte[] decode2 = RSACoder.decryptByPrivateKey(Base64.decodeBase64(str), Base64.decodeBase64(privateKey)); // System.out.println("甲方解密后的数据:" + new String(decode2)); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/util/RestTemplateUtil.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/util/RestTemplateUtil.java
package redisson.util; import org.springframework.http.*; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.util.Map; public class RestTemplateUtil { public static String postForJson(String url, String json) { HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); HttpEntity<String> entity = new HttpEntity<String>(json, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class); return response.getBody(); } public static String postForEntity(String url, MultiValueMap<String, String> map) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); return response.getBody(); } public static String postForEntity(String url, String json) { HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); HttpEntity<String> entity = new HttpEntity<String>(json, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class); return response.getBody(); } public static String getForEntity(String url, Map<String, Object> map,Map<String,String> headerMap) { HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); if(headerMap != null) { for (String key : headerMap.keySet()) { headers.add(key, headerMap.get(key)); } } HttpEntity<Map<String, Object>> entity = new HttpEntity<Map<String, Object>>(headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class,map); return response.getBody(); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/util/DESCoder.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/util/DESCoder.java
package redisson.util; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.SecureRandom; public class DESCoder { /** * 加密 * * @param datasource byte[] * @param password String * @return byte[] */ public static String encrypt(byte[] datasource, String password) { try { SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象,ENCRYPT_MODE用于将 Cipher 初始化为加密模式的常量 cipher.init(Cipher.ENCRYPT_MODE, securekey, random); // 现在,获取数据并加密 正式执行加密操作 // 按单部分操作加密或解密数据,或者结束一个多部分操作 return Base64.encodeBase64String((cipher.doFinal(datasource))); } catch (Throwable e) { e.printStackTrace(); } return null; } /** * 解密 * * @param src byte[] * @param password String * @return byte[] * @throws Exception */ public static String decrypt(byte[] src, String password) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom random = new SecureRandom(); // 创建一个DESKeySpec对象 DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 创建一个密匙工厂 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 返回实现指定转换的 Cipher 对象 // 将DESKeySpec对象转换成SecretKey对象 SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, random); // 真正开始解密操作 return new String(cipher.doFinal(src)); } @SuppressWarnings("restriction") public static String encrypt(String input, String key) { String result = ""; if (input != null) { try { SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, securekey, random); result = new sun.misc.BASE64Encoder().encode(cipher.doFinal(input.getBytes())).replace("\r", "\\r") .replace("\n", "\\n"); } catch (Exception e) { e.printStackTrace(); } } return result; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/util/AideUtil.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/util/AideUtil.java
package redisson.util; import redisson.contants.Codes; import redisson.contants.Messages; import redisson.exception.BusinessException; import java.lang.reflect.Field; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.UUID; public class AideUtil { public static String createUUId() { return UUID.randomUUID().toString().replace("-", ""); } /** * key拼接日期yyyyMMddHH * * @param key * @return */ public static String redisKeyAppenNowDate(String key) { SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH"); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); String time = df.format(calendar.getTime()); return key + time; } public static Long getCustomTimestamp() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime dateTime = LocalDateTime.parse(formatter.format(LocalDateTime.now()), formatter); return Timestamp.valueOf(dateTime).getTime(); } /** * 验证对象每个属性都不为空值 * * @param t */ public static <T> void validateParams(T t) { try { for (Field f : t.getClass().getDeclaredFields()) { f.setAccessible(true); if (f.get(t) == null || f.get(t).equals("")) { throw new BusinessException(Codes.CODE_500, Messages.PARAMS_NULL); } } } catch (BusinessException e) { throw new BusinessException(Codes.CODE_500, e.getMessage()); } catch (Exception e) { throw new BusinessException(Codes.CODE_500, Messages.SYSTEM_EXCEPTION); } } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/redis/RedisCache.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/redis/RedisCache.java
package redisson.redis; //@Component public class RedisCache { // @Autowired // private RedisTemplate<String, Object> redisTemplate; // /** // * 获取指定键的值(String) // * // * @param key // * @return // */ // public String getForValue(String key) { // Object obj = this.redisTemplate.opsForValue().get(key); // return obj == null ? "" : obj.toString(); // } // // /** // * 设置指定键的值(String) // * // * @param key // * @param value // */ // public void putForValue(String key, String value) { // this.redisTemplate.opsForValue().set(key, value); // } // // /** // * 设置指定键的值带过期时间(String) // * // * @param key // * @param value // */ // public void putForValue(String key, String value, long timeout, TimeUnit unit) { // this.redisTemplate.opsForValue().set(key, value, timeout, unit); // } // // /** // * 根据指定键删除值(String) // * // * @param key // * @return // */ // public boolean deleteForValue(String key) { // return this.redisTemplate.delete(key); // } // // /** // * 获取哈希结构指定键的值(Hash) // * // * @param key // * @param field // * @return // */ // public String getForHash(String key, String field) { // return this.redisTemplate.opsForHash().get(key, field).toString(); // } // // /** // * 设置哈希结构指定键的值(Hash) // * // * @param redisKey // * @param key // * @param value // */ // public void putForHash(String redisKey, String key, String value) { // this.redisTemplate.opsForHash().put(redisKey, key, value); // } // // /** // * 获取哈希结构指定键的值集合(Hash) // * // * @param key // * @return // */ // public Map<Object, Object> getForHash(String key) { // return this.redisTemplate.opsForHash().entries(key); // } // // /** // * 根据key删除一个或多个哈希结构的值(Hash) // * // * @param key // * @param fields // * @return // */ // public Long deleteForHash(String redisKey, Object... keys) { // return this.redisTemplate.opsForHash().delete(redisKey, keys); // } // // /** // * 根据一个Set结构的key判断值是否在其中(Set) // * // * @param key // * @param value // * @return // */ // public boolean isMemberForSet(String key, String value) { // return this.redisTemplate.opsForSet().isMember(key, value); // } // // /** // * 根据一个Set结构的key设置值(Set) // * // * @param key // * @param values // * @return // */ // public Long putForSet(String key, Object... values) { // return this.redisTemplate.opsForSet().add(key, values); // } // // /** // * 加锁 // * // * @return // */ // public String lock(String key, String value, long expire) { // String result = this.redisTemplate.execute(new RedisCallback<String>() { // @Override // public String doInRedis(RedisConnection connection) throws DataAccessException { // JedisCommands commands = (JedisCommands) connection.getNativeConnection(); // return commands.set(key, value, "NX", "EX", expire); // } // }); // return result; // } // // /** // * 存储在list头部 // * // * @param key // * @param value // * @return // */ // public Long leftPushForList(String key, Object value) { // return redisTemplate.opsForList().leftPush(key, value); // } // // /** // * 设置过期时间 // * // * @param key // * @param timeout // * @param unit // * @return // */ // public Boolean expire(String key, long timeout, TimeUnit unit) { // return redisTemplate.expire(key, timeout, unit); // } // // /** // * 增加(自增长), 负数则为自减 // * // * @param key // * @return // */ // public Long incrementForValue(String key, long increment) { // return redisTemplate.opsForValue().increment(key, increment); // } // // /** // * 为哈希表 key 中的指定字段的整数值加上增量 increment // * // * @param key // * @param field // * @param delta // * @return // */ // public Double incrementForHash(String key, Object field, double delta) { // return redisTemplate.opsForHash().increment(key, field, delta); // } // // /** // * 获取列表长度 // * // * @param key // * @return // */ // public Long sizeForList(String key) { // return redisTemplate.opsForList().size(key); // } // // /** // * 移除并获取列表最后一个元素 // * // * @param key // * @return 删除的元素 // */ // public Object rightPopForList(String key) { // return redisTemplate.opsForList().rightPop(key); // } // // /** // * 获取集合的元素, 从小到大排序 // * // * @param key // * @param start 开始位置 // * @param end 结束位置, -1查询所有 // * @return // */ // public List<Object> rangeForList(String key, long start, long end) { // return redisTemplate.opsForList().range(key, start, end); // } // // /** // * 获取哈希表中所有值 // * // * @param key // * @return // */ // public List<Object> getValuesForHash(String key) { // return redisTemplate.opsForHash().values(key); // } // // public <T> void putForHashAll(String key, Map<T, T> map) { // redisTemplate.opsForHash().putAll(key, map); // } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/exception/BusinessException.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/exception/BusinessException.java
package redisson.exception; public class BusinessException extends RuntimeException { private static final long serialVersionUID = 1L; public int code; private String message; public BusinessException() { super(); } public BusinessException(String msg) { super(msg); this.message = msg; } public BusinessException(int code, String msg) { super(msg); this.code = code; this.message = msg; } public BusinessException(String msg, Throwable cause) { super(msg, cause); this.message = msg; } public BusinessException(Throwable cause, String msg) { super(msg, cause); this.message = msg; } public BusinessException(Throwable cause) { super(cause); } public String getMessage() { return message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public void setMessage(String message) { this.message = message; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/exception/GlobalExceptionHandler.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/exception/GlobalExceptionHandler.java
package redisson.exception; import com.dyuproject.protostuff.ProtobufException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ui.Model; import org.springframework.validation.BindException; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import redisson.bean.vo.ResultVO; import redisson.contants.Codes; import redisson.contants.Messages; import javax.servlet.http.HttpServletRequest; import java.util.List; @ResponseBody @ControllerAdvice public class GlobalExceptionHandler { private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 自定义异常 * * @param request * @param exception * @return * @throws Exception */ @ExceptionHandler(value = BusinessException.class) public Object businessHandler(HttpServletRequest request, BusinessException exception, Model model) throws Exception { return new ResultVO<String>(exception.getCode(), exception.getMessage()); } /** * Protobuf序列化/反序列化异常 * * @param request * @param exception * @param model * @return * @throws Exception */ @ExceptionHandler(value = ProtobufException.class) public Object protobufHandler(HttpServletRequest request, ProtobufException exception, Model model) throws Exception { logger.error(Messages.DESERIALIZATION_ERROR, exception); return new ResultVO<String>(Codes.CODE_500, exception.getMessage()); } /** * 参数验证异常 * * @param request * @param exception * @param model * @return * @throws Exception */ @ExceptionHandler(value = BindException.class) public Object validationHandler(HttpServletRequest request, BindException exception, Model model) throws Exception { logger.error(Messages.VALIDATION_ERROR, exception); List<ObjectError> allErrors = exception.getAllErrors(); ObjectError error = allErrors.get(0); String defaultMessage = error.getDefaultMessage(); return new ResultVO<String>(Codes.CODE_500, defaultMessage); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/contants/Codes.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/contants/Codes.java
package redisson.contants; public class Codes { public static final int CODE_200 = 200; public static final int CODE_500 = 500; public static final int CODE_601 = 601; public static final int CODE_602 = 602; public static final int CODE_405 = 405; }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/contants/Messages.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/contants/Messages.java
package redisson.contants; public class Messages { public static final String KEYWORDS_SUCCESS = "成功"; public static final String NUMBER_INVALID = "数字无效"; public static final String TIME_INTERVAL_IS_TOO_LONG = "时间间隔太长"; public static final String DECRYPTP_PARAMETER_ERROR = "解密参数出现错误"; public static final String ORDER_NOT_EXIST = "订单不存在"; public static final String OPERATOR_ILLEGAL = "操作人非法"; public static final String USER_TOKEN_EXPIRED = "用户token已过期"; public static final String USER_TOKEN_ERROR = "用户token不正确"; public static final String METHED_NOT_ALLOW = "方法不被允许"; public static final String AUTH_FAIL = "认证不通过"; public static final String DESERIALIZATION_ERROR = "反序列化出现错误"; public static final String VALIDATION_ERROR = "参数验证错误"; public static final String AGIO_UNFREEZE_TEXT = "差价解冻"; public static final String COLDMONEY_HAS_NOT_UNFREEZE = "冻结资产不足,解冻失败"; public static final String ORDER_FEE_DEDUCTION_ERROR = "订单手续费抵扣异常"; public static final String TURNTABLE_TRADING_ERROR = "转盘成交得到次数异常"; public static final String PRIZE_FEE_DEDUCTION_ERROR = "奖品券抵扣手续费"; public static final String SUPER_PARTNER_FEE_FAILURE = "超级伙伴分账失败"; public static final String USER_NOT_FOUND = "用户不存在"; public static final String NORMAL_SELF_MSG = "普通返佣,自得"; public static final String NORMAL_SHARE_MSG = "普通返佣,分账"; public static final String ONE_SUPER_SHARE_MSG = "一级关系,超级合伙人返佣分账"; public static final String TWO_SUPER_SHARE_MSG = "二级关系,超级合伙人返佣分账"; public static final String ONE_LEVEL = "一级关系"; public static final String SECOND_LEVEL = "二级关系"; public static final String NORMAL_LEVEL = "普通返佣"; public static final String ORDER_PUT_REDIS_ERROR = "订单放入redis异常"; public static final String REQUEST_PARAMETER_NOT_NULL = "请求参数不能为空"; public static final String QUERY_MARKET_PARAMETERS_ERROR = "查询市场所需参数异常"; public static final String PARAMS_NULL = "参数有误"; public static final String SYSTEM_EXCEPTION = "系统异常"; public static final String ENTRUST_ALREADY_CANCEL = "当前委托已撤销"; public static final String ENTRUST_ALREADY_TRADE = "当前委托已成交"; public static final String ENTRUST_ISNULL = "委托不存在"; public static final String ENTRUST_TRANDING = "您的委托正在成交中,请稍后再试"; public static final String ASSET_ACCOUNT_IS_NULL = "资产主表不存在"; public static final String CANCEL_VERSION_RETRY_COUNT_EXCEED = "撤销委托版本号重试达到次数"; public static final String CANCEL_VERSION_RETRY_ERROR = "撤销委托版本号重试失败"; public static final String ACTIVITY_VERSION_RETRY_COUNT_EXCEED = "活动版本号重试达到次数"; public static final String ACTIVITY_VERSION_RETRY_ERROR = "活动版本号重试失败"; public static final String BT_VERSION_RETRY_COUNT_EXCEED = "BT抵扣版本号重试达到次数"; public static final String BT_VERSION_RETRY_ERROR = "BT抵扣版本号重试失败"; public static final String BT_SENDBACK_RETRY_COUNT_EXCEED = "BT抵扣退手续费版本号重试达到次数"; public static final String BT_SENDBACK_VERSION_RETRY_ERROR = "BT抵扣退手续费版本号重试失败"; public static final String VIP_VERSION_RETRY_COUNT_EXCEED = "VIP等级手续费抵扣版本号重试达到次数"; public static final String VIP_VERSION_RETRY_ERROR = "VIP等级手续费抵扣版本号重试失败"; public static final String ALREADY_RETRY = "已重试"; public static final String INITIAL_ASSET_ERROR = "初始化资产失败"; }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/contants/Datas.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/contants/Datas.java
package redisson.contants; public class Datas { public static final String OK = "OK"; public static final String ENTRUST_TYPE_BUY = "1"; public static final String ENTRUST_TYPE_SELL = "2"; /** 委托类型-买-1 */ public static final int ENTRUST_TYPE_BUY_INT = 1; /** 委托类型-卖-2 */ public static final int ENTRUST_TYPE_SELL_INT = 2; public static final String ACCESS_TOKEN_EXPIRED = "Access token expired"; /** 资产流水类型-加-1 */ public static final int ASSET_TYPE_ADD = 1; /** 资产流水类型-减-2 */ public static final int ASSET_TYPE_LESS = 2; /** 资产streamType-其他-10 */ public static final int ASSET_STREAM_TYPE_OTHER = 10; /** 当前委托-1 */ public static final int CURRENT_ENTRUST_TYPE = 1; /** 历史委托-2 */ public static final int HISTORY_ENTRUST_TYPE = 2; /** * 委托状态-已撤销-1 */ public static final int ENTRUST_STATUS_CANCEL = 1; /** * 委托状态-已成交-2 */ public static final int ENTRUST_STATUS_TRADE = 2; public static final String UNFREEZE_TEXT = "解冻"; public static final String FREEZE_TEXT = "冻结"; public static final String EUNIT_CNT = "CNT"; /** * 提前还款费率 */ public static final double ADVANCE_REPAY_DEFAULT_RATE = 0.1; public static final double ADVANCE_REPAY_RETURN_RATE = 0.9; }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/bean/po/Entrust.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/bean/po/Entrust.java
package redisson.bean.po; import java.math.BigDecimal; import java.util.Date; public class Entrust { private String id; private String entrustNo; private String userId; private String memberId; private Integer cycle; private String pawnCoinId; private String pawnCoinEunit; private BigDecimal pawnTotalQuantity; private BigDecimal pawnTradeQuantity; private BigDecimal pawnRate; private String legalCoinId; private String legalCoinEunit; private BigDecimal legalTotalQuantity; private BigDecimal legalTradeQuantity; private BigDecimal legalDailyRate; private BigDecimal totalInterest; private Integer type; private Integer status; private Date createTime; private Date updateTime; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getEntrustNo() { return entrustNo; } public void setEntrustNo(String entrustNo) { this.entrustNo = entrustNo == null ? null : entrustNo.trim(); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId == null ? null : memberId.trim(); } public Integer getCycle() { return cycle; } public void setCycle(Integer cycle) { this.cycle = cycle; } public String getPawnCoinId() { return pawnCoinId; } public void setPawnCoinId(String pawnCoinId) { this.pawnCoinId = pawnCoinId == null ? null : pawnCoinId.trim(); } public String getPawnCoinEunit() { return pawnCoinEunit; } public void setPawnCoinEunit(String pawnCoinEunit) { this.pawnCoinEunit = pawnCoinEunit == null ? null : pawnCoinEunit.trim(); } public BigDecimal getPawnTotalQuantity() { return pawnTotalQuantity; } public void setPawnTotalQuantity(BigDecimal pawnTotalQuantity) { this.pawnTotalQuantity = pawnTotalQuantity; } public BigDecimal getPawnTradeQuantity() { return pawnTradeQuantity; } public void setPawnTradeQuantity(BigDecimal pawnTradeQuantity) { this.pawnTradeQuantity = pawnTradeQuantity; } public BigDecimal getPawnRate() { return pawnRate; } public void setPawnRate(BigDecimal pawnRate) { this.pawnRate = pawnRate; } public String getLegalCoinId() { return legalCoinId; } public void setLegalCoinId(String legalCoinId) { this.legalCoinId = legalCoinId == null ? null : legalCoinId.trim(); } public String getLegalCoinEunit() { return legalCoinEunit; } public void setLegalCoinEunit(String legalCoinEunit) { this.legalCoinEunit = legalCoinEunit == null ? null : legalCoinEunit.trim(); } public BigDecimal getLegalTotalQuantity() { return legalTotalQuantity; } public void setLegalTotalQuantity(BigDecimal legalTotalQuantity) { this.legalTotalQuantity = legalTotalQuantity; } public BigDecimal getLegalTradeQuantity() { return legalTradeQuantity; } public void setLegalTradeQuantity(BigDecimal legalTradeQuantity) { this.legalTradeQuantity = legalTradeQuantity; } public BigDecimal getLegalDailyRate() { return legalDailyRate; } public void setLegalDailyRate(BigDecimal legalDailyRate) { this.legalDailyRate = legalDailyRate; } public BigDecimal getTotalInterest() { return totalInterest; } public void setTotalInterest(BigDecimal totalInterest) { this.totalInterest = totalInterest; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/bean/po/Order.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/bean/po/Order.java
package redisson.bean.po; import java.math.BigDecimal; import java.util.Date; public class Order { private String id; private String orderNo; private String entrustId; private String entrustNo; private String userId; private String memberId; private String otherUserId; private String otherMemberId; private Integer cycle; private String pawnCoinId; private String pawnCoinEunit; private BigDecimal pawnQuantity; private BigDecimal pawnRate; private String legalCoinId; private String legalCoinEunit; private BigDecimal legalQuantity; private BigDecimal legalDailyRate; private BigDecimal warnPrice; private BigDecimal closePrice; private BigDecimal fee; private Integer alreadyInterestCount; private BigDecimal dailyInterest; private BigDecimal alreadyInterest; private BigDecimal totalInterest; private Integer type; private Integer direction; private Integer status; private Date createTime; private Date updateTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public String getEntrustId() { return entrustId; } public void setEntrustId(String entrustId) { this.entrustId = entrustId; } public String getEntrustNo() { return entrustNo; } public void setEntrustNo(String entrustNo) { this.entrustNo = entrustNo; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getOtherUserId() { return otherUserId; } public void setOtherUserId(String otherUserId) { this.otherUserId = otherUserId; } public String getOtherMemberId() { return otherMemberId; } public void setOtherMemberId(String otherMemberId) { this.otherMemberId = otherMemberId; } public Integer getCycle() { return cycle; } public void setCycle(Integer cycle) { this.cycle = cycle; } public String getPawnCoinId() { return pawnCoinId; } public void setPawnCoinId(String pawnCoinId) { this.pawnCoinId = pawnCoinId; } public String getPawnCoinEunit() { return pawnCoinEunit; } public void setPawnCoinEunit(String pawnCoinEunit) { this.pawnCoinEunit = pawnCoinEunit; } public BigDecimal getPawnQuantity() { return pawnQuantity; } public void setPawnQuantity(BigDecimal pawnQuantity) { this.pawnQuantity = pawnQuantity; } public BigDecimal getPawnRate() { return pawnRate; } public void setPawnRate(BigDecimal pawnRate) { this.pawnRate = pawnRate; } public String getLegalCoinId() { return legalCoinId; } public void setLegalCoinId(String legalCoinId) { this.legalCoinId = legalCoinId; } public String getLegalCoinEunit() { return legalCoinEunit; } public void setLegalCoinEunit(String legalCoinEunit) { this.legalCoinEunit = legalCoinEunit; } public BigDecimal getLegalQuantity() { return legalQuantity; } public void setLegalQuantity(BigDecimal legalQuantity) { this.legalQuantity = legalQuantity; } public BigDecimal getLegalDailyRate() { return legalDailyRate; } public void setLegalDailyRate(BigDecimal legalDailyRate) { this.legalDailyRate = legalDailyRate; } public BigDecimal getWarnPrice() { return warnPrice; } public void setWarnPrice(BigDecimal warnPrice) { this.warnPrice = warnPrice; } public BigDecimal getClosePrice() { return closePrice; } public void setClosePrice(BigDecimal closePrice) { this.closePrice = closePrice; } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public Integer getAlreadyInterestCount() { return alreadyInterestCount; } public void setAlreadyInterestCount(Integer alreadyInterestCount) { this.alreadyInterestCount = alreadyInterestCount; } public BigDecimal getDailyInterest() { return dailyInterest; } public void setDailyInterest(BigDecimal dailyInterest) { this.dailyInterest = dailyInterest; } public BigDecimal getAlreadyInterest() { return alreadyInterest; } public void setAlreadyInterest(BigDecimal alreadyInterest) { this.alreadyInterest = alreadyInterest; } public BigDecimal getTotalInterest() { return totalInterest; } public void setTotalInterest(BigDecimal totalInterest) { this.totalInterest = totalInterest; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getDirection() { return direction; } public void setDirection(Integer direction) { this.direction = direction; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/bean/vo/ResultVO.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/bean/vo/ResultVO.java
package redisson.bean.vo; public class ResultVO<T> { /** * 状态码 */ private Integer code; /** * 信息 */ private String message; /** * 返回数据 */ private T data; public ResultVO() { } public ResultVO(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } public ResultVO(int code, String message) { this.code = code; this.message = message; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/bean/bo/SecretBO.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/bean/bo/SecretBO.java
package redisson.bean.bo; public class SecretBO { private String ciphertext; private String key; private String time; public String getCiphertext() { return ciphertext; } public void setCiphertext(String ciphertext) { this.ciphertext = ciphertext; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/TaskExecutePool.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/TaskExecutePool.java
package redisson.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.SchedulingTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; @Configuration public class TaskExecutePool { @Value("${spring.task.pool.corePoolSize}") private int corePoolSize; @Value("${spring.task.pool.maxPoolSize}") private int maxPoolSize; @Value("${spring.task.pool.keepAliveSeconds}") private int keepAliveSeconds; @Value("${spring.task.pool.queueCapacity}") private int queueCapacity; @Bean public Executor initTaskAsyncPool() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(keepAliveSeconds); executor.setKeepAliveSeconds(queueCapacity); executor.setThreadNamePrefix("MyExecutor-"); // rejection-policy:当pool已经达到max size的时候,如何处理新任务 // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } @Bean public SchedulingTaskExecutor initSchedulingTaskExecutor() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(100); scheduler.setThreadNamePrefix("MyScheduler-"); return scheduler; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/RedisConfiguration.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/RedisConfiguration.java
package redisson.config;//package org.bifu.coin.aide.config; // //import org.redisson.spring.starter.RedissonProperties; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.beans.factory.annotation.Value; //import org.springframework.cache.Cache; //import org.springframework.cache.CacheManager; //import org.springframework.cache.annotation.CachingConfigurerSupport; //import org.springframework.cache.annotation.EnableCaching; //import org.springframework.cache.interceptor.CacheErrorHandler; //import org.springframework.cache.interceptor.KeyGenerator; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Scope; //import org.springframework.data.redis.cache.RedisCacheManager; //import org.springframework.data.redis.connection.RedisPassword; //import org.springframework.data.redis.connection.RedisStandaloneConfiguration; //import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; //import org.springframework.data.redis.core.RedisTemplate; //import org.springframework.data.redis.serializer.RedisSerializer; //import org.springframework.data.redis.serializer.StringRedisSerializer; // ////@Configuration ////@EnableCaching //public class RedisConfiguration extends CachingConfigurerSupport { // // private static final Logger logger = LoggerFactory.getLogger(RedisConfiguration.class); // // @Autowired // private JedisConnectionFactory jedisConnectionFactory; // // @Autowired // private RedissonProperties redissonProperties; // // @Value("${spring.redis.database0}") // private Integer database0; // @Value("${spring.redis.host}") // private String host; // @Value("${spring.redis.password}") // private String password; // @Value("${spring.redis.port}") // private int port; // @Value("${spring.redis.timeout}") // private int timeout; // @Value("${spring.redis.jedis.pool.max-idle}") // private int maxIdle; // @Value("${spring.redis.jedis.pool.max-wait}") // private long maxWaitMillis; // // public RedisStandaloneConfiguration getRedisStandaloneConfiguration(Integer database) { // RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration("47.104.130.105", 6379); // configuration.setPassword(RedisPassword.of("123456")); // configuration.setDatabase(database); // return configuration; // } // // @Scope(scopeName = "prototype") // public JedisConnectionFactory jedisConnectionFactory(Integer database) { // logger.info("Create JedisConnectionFactory successful"); // RedisStandaloneConfiguration configuration = getRedisStandaloneConfiguration(database); // return new JedisConnectionFactory(configuration); // } // // @Bean // @Override // public KeyGenerator keyGenerator() { // // 设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存 // // 使用:进行分割,可以很多显示出层级关系 // // 这里其实就是new了一个KeyGenerator对象,采用lambda表达式的写法 // return (target, method, params) -> { // StringBuilder sb = new StringBuilder(); // sb.append(target.getClass().getName()); // sb.append(":"); // sb.append(method.getName()); // for (Object obj : params) { // sb.append(":" + String.valueOf(obj)); // } // String rsToUse = String.valueOf(sb); // logger.info("自动生成Redis Key -> [{}]", rsToUse); // return rsToUse; // }; // } // // @Bean // @Override // public CacheManager cacheManager() { // // 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,这里默认没有配置 // logger.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start"); // RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder // .fromConnectionFactory(jedisConnectionFactory); // return builder.build(); // } // // @Bean // public RedisTemplate<String, Object> redisTemplate() { // // 配置redisTemplate // JedisConnectionFactory jedisConnectionFactory = jedisConnectionFactory(database0); // RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); // redisTemplate.setConnectionFactory(jedisConnectionFactory); // RedisSerializer<?> stringSerializer = new StringRedisSerializer(); // redisTemplate.setKeySerializer(stringSerializer); // key序列化 // redisTemplate.setValueSerializer(stringSerializer); // value序列化 // redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化 // redisTemplate.setHashValueSerializer(stringSerializer); // Hash value序列化 // redisTemplate.afterPropertiesSet(); // return redisTemplate; // } // // @Override // @Bean // public CacheErrorHandler errorHandler() { // // 异常处理,当Redis发生异常时,打印日志,但是程序正常走 // logger.info("初始化 -> [{}]", "Redis CacheErrorHandler"); // CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() { // @Override // public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { // logger.error("Redis occur handleCacheGetError:key -> [{}]", key, e); // } // // @Override // public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { // logger.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e); // } // // @Override // public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { // logger.error("Redis occur handleCacheEvictError:key -> [{}]", key, e); // } // // @Override // public void handleCacheClearError(RuntimeException e, Cache cache) { // logger.error("Redis occur handleCacheClearError:", e); // } // }; // return cacheErrorHandler; // } // //}
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/mq/RedissonMQListener.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/mq/RedissonMQListener.java
package redisson.config.tingyu.mq; import org.redisson.api.RPatternTopic; import org.redisson.api.RTopic; import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.ReflectionUtils; import redisson.config.tingyu.annotation.MQListener; /** * mq监听 */ public class RedissonMQListener implements BeanPostProcessor { Logger logger = LoggerFactory.getLogger(RedissonMQListener.class); @Autowired private RedissonClient redissonClient; @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { ReflectionUtils.doWithMethods(bean.getClass(), method -> { MQListener annotation = AnnotationUtils.findAnnotation(method, MQListener.class); if(annotation!=null){ switch (annotation.model()){ case PRECISE: RTopic topic = redissonClient.getTopic(annotation.name()); logger.info("注解redisson精准监听器name={}",annotation.name()); topic.addListener(Object.class, (channel, msg) -> { try { Object[] aras=new Object[method.getParameterTypes().length]; int index=0; for (Class parameterType : method.getParameterTypes()) { String simpleName = parameterType.getSimpleName(); if("CharSequence".equals(simpleName)){ aras[index++]=channel; }else if (msg.getClass().getSimpleName().equals(simpleName)||"Object".equals(simpleName)){ aras[index++]=msg; }else { aras[index++]=null; } } method.invoke(bean,aras); } catch (Exception e) { throw new RuntimeException(e); } }); break; case PATTERN: RPatternTopic patternTopic = redissonClient.getPatternTopic(annotation.name()); logger.info("注解redisson模糊监听器name={}",annotation.name()); patternTopic.addListener(Object.class, (pattern, channel, msg) -> { try { Object[] aras=new Object[method.getParameterTypes().length]; int index=0; boolean patternFlag = false; for (Class parameterType : method.getParameterTypes()) { String simpleName = parameterType.getSimpleName(); if("CharSequence".equals(simpleName)){ if(!patternFlag){ patternFlag=true; aras[index++]=pattern; }else { aras[index++]=channel; } }else if (msg.getClass().getSimpleName().equals(simpleName)||"Object".equals(simpleName)){ aras[index++]=msg; }else { aras[index++]=null; } } method.invoke(bean,aras); } catch (Exception e) { throw new RuntimeException(e); } }); break; } } }, ReflectionUtils.USER_DECLARED_METHODS); return bean; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/aop/LockAop.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/aop/LockAop.java
package redisson.config.tingyu.aop; 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.aspectj.lang.reflect.MethodSignature; import org.redisson.RedissonMultiLock; import org.redisson.RedissonRedLock; import org.redisson.api.RLock; import org.redisson.api.RReadWriteLock; import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.annotation.Order; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import redisson.config.tingyu.annotation.Lock; import redisson.config.tingyu.enums.LockModel; import redisson.config.tingyu.excepiton.LockException; import redisson.config.tingyu.properties.RedissonProperties; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * 分布式锁aop */ @Aspect @Order(-10) public class LockAop { private Logger log = LoggerFactory.getLogger(getClass()); @Autowired private RedissonProperties redissonProperties; @Autowired private RedissonClient redissonClient; @Pointcut("@annotation(lock)") public void controllerAspect(Lock lock) { } /** * 通过spring Spel 获取参数 * @param key 定义的key值 以#开头 例如:#user * @param parameterNames 形参 * @param values 形参值 * @param keyConstant key的常亮 * @return */ public List<String> getVauleBySpel(String key, String[] parameterNames, Object[] values, String keyConstant) { List<String> keys=new ArrayList<>(); if(!key.contains("#")){ String s = "redisson:lock:" + key+keyConstant; log.info("没有使用spel表达式value->{}",s); keys.add(s); return keys; } //spel解析器 ExpressionParser parser = new SpelExpressionParser(); //spel上下文 EvaluationContext context = new StandardEvaluationContext(); for (int i = 0; i < parameterNames.length; i++) { context.setVariable(parameterNames[i], values[i]); } Expression expression = parser.parseExpression(key); Object value = expression.getValue(context); if(value!=null){ if(value instanceof List){ List value1 = (List) value; for (Object o : value1) { keys.add("redisson:lock:" + o.toString()+keyConstant); } }else if(value.getClass().isArray()){ Object[] obj= (Object[]) value; for (Object o : obj) { keys.add("redisson:lock:" + o.toString()+keyConstant); } }else { keys.add("redisson:lock:" + value.toString()+keyConstant); } } log.info("spel表达式key={},value={}",key,keys); return keys; } @Around("controllerAspect(lock)") public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint, Lock lock) throws Throwable { String[] keys = lock.keys(); if (keys.length == 0) { throw new RuntimeException("keys不能为空"); } String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(((MethodSignature) proceedingJoinPoint.getSignature()).getMethod()); Object[] args = proceedingJoinPoint.getArgs(); long attemptTimeout = lock.attemptTimeout(); if (attemptTimeout == 0) { attemptTimeout = redissonProperties.getAttemptTimeout(); } long lockWatchdogTimeout = lock.lockWatchdogTimeout(); if (lockWatchdogTimeout == 0) { lockWatchdogTimeout = redissonProperties.getLockWatchdogTimeout(); } LockModel lockModel = lock.lockModel(); if (lockModel.equals(LockModel.AUTO)) { LockModel lockModel1 = redissonProperties.getLockModel(); if (lockModel1 != null) { lockModel = lockModel1; } else if (keys.length > 1) { lockModel = LockModel.REDLOCK; } else { lockModel = LockModel.REENTRANT; } } if (!lockModel.equals(LockModel.MULTIPLE) && !lockModel.equals(LockModel.REDLOCK) && keys.length > 1) { throw new RuntimeException("参数有多个,锁模式为->" + lockModel.name() + ".无法锁定"); } log.info("锁模式->{},等待锁定时间->{}秒.锁定最长时间->{}秒",lockModel.name(),attemptTimeout/1000,lockWatchdogTimeout/1000); boolean res = false; RLock rLock = null; //一直等待加锁. switch (lockModel) { case FAIR: rLock = redissonClient.getFairLock(getVauleBySpel(keys[0],parameterNames,args,lock.keyConstant()).get(0)); break; case REDLOCK: List<RLock> rLocks=new ArrayList<>(); for (String key : keys) { List<String> vauleBySpel = getVauleBySpel(key, parameterNames, args, lock.keyConstant()); for (String s : vauleBySpel) { rLocks.add(redissonClient.getLock(s)); } } RLock[] locks=new RLock[rLocks.size()]; int index=0; for (RLock r : rLocks) { locks[index++]=r; } rLock = new RedissonRedLock(locks); break; case MULTIPLE: rLocks=new ArrayList<>(); for (String key : keys) { List<String> vauleBySpel = getVauleBySpel(key, parameterNames, args, lock.keyConstant()); for (String s : vauleBySpel) { rLocks.add(redissonClient.getLock(s)); } } locks=new RLock[rLocks.size()]; index=0; for (RLock r : rLocks) { locks[index++]=r; } rLock = new RedissonMultiLock(locks); break; case REENTRANT: List<String> vauleBySpel = getVauleBySpel(keys[0], parameterNames, args, lock.keyConstant()); //如果spel表达式是数组或者LIST 则使用红锁 if(vauleBySpel.size()==1){ rLock= redissonClient.getLock(vauleBySpel.get(0)); }else { locks=new RLock[vauleBySpel.size()]; index=0; for (String s : vauleBySpel) { locks[index++]=redissonClient.getLock(s); } rLock = new RedissonRedLock(locks); } break; case READ: RReadWriteLock rwlock = redissonClient.getReadWriteLock(getVauleBySpel(keys[0],parameterNames,args, lock.keyConstant()).get(0)); rLock = rwlock.readLock(); break; case WRITE: RReadWriteLock rwlock1 = redissonClient.getReadWriteLock(getVauleBySpel(keys[0],parameterNames,args, lock.keyConstant()).get(0)); rLock = rwlock1.writeLock(); break; } //执行aop if(rLock!=null) { try { if (attemptTimeout == -1) { res = true; //一直等待加锁 rLock.lock(lockWatchdogTimeout, TimeUnit.MILLISECONDS); } else { res = rLock.tryLock(attemptTimeout, lockWatchdogTimeout, TimeUnit.MILLISECONDS); } if (res) { Object obj = proceedingJoinPoint.proceed(); return obj; }else{ throw new LockException("获取锁失败"); } } finally { if (res) { rLock.unlock(); } } } throw new LockException("获取锁失败"); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/aop/MQAop.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/aop/MQAop.java
package redisson.config.tingyu.aop; 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.redisson.api.RTopic; import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import redisson.config.tingyu.annotation.MQPublish; /** * MQ发送消息AOP */ @Aspect public class MQAop { private Logger log = LoggerFactory.getLogger(getClass()); @Autowired private RedissonClient redissonClient; @Pointcut("@annotation(mq)") public void aspect(MQPublish mq) { } @Around("aspect(mq)") public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint, MQPublish mq) { try { Object obj = proceedingJoinPoint.proceed(); RTopic topic = redissonClient.getTopic(mq.name()); topic.publish(obj); return obj; } catch (Throwable e) { throw new RuntimeException(e); } } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/configuration/CacheConfiguration.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/configuration/CacheConfiguration.java
package redisson.config.tingyu.configuration; import org.redisson.api.RedissonClient; import org.redisson.spring.cache.CacheConfig; import org.redisson.spring.cache.RedissonSpringCacheManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportAware; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import redisson.config.tingyu.annotation.EnableCache; import redisson.config.tingyu.properties.RedissonProperties; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; /** * MQ配置 */ @Configuration @EnableCaching @EnableConfigurationProperties(value = RedissonProperties.class) public class CacheConfiguration implements ImportAware { private String[] value = {"testCache"}; Logger logger = LoggerFactory.getLogger(CacheConfiguration.class); /** * 缓存时间 默认30分钟 * @return */ private long ttl = 18000; /** * 最长空闲时间 默认30分钟 * @return */ private long maxIdleTime = 18000; @Resource private RedissonClient redissonClient; @Autowired private RedissonProperties redissonProperties; @Bean CacheManager cacheManager() { Map<String, CacheConfig> config = new HashMap<>(); // 创建一个名称为"testMap"的缓存,过期时间ttl为24分钟,同时最长空闲时maxIdleTime为12分钟。 for (String s : value) { logger.info("初始化spring cache空间{}",s); config.put(s, new CacheConfig(ttl, maxIdleTime)); } return new RedissonSpringCacheManager(redissonClient, config); } @Override public void setImportMetadata(AnnotationMetadata importMetadata) { Map<String, Object> enableAttrMap = importMetadata .getAnnotationAttributes(EnableCache.class.getName()); AnnotationAttributes enableAttrs = AnnotationAttributes.fromMap(enableAttrMap); this.value=enableAttrs.getStringArray("value"); this.maxIdleTime=enableAttrs.getNumber("maxIdleTime"); this.ttl=enableAttrs.getNumber("ttl"); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/configuration/RedissonConfiguration.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/configuration/RedissonConfiguration.java
package redisson.config.tingyu.configuration; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.client.codec.Codec; import org.redisson.config.*; import org.redisson.connection.balancer.LoadBalancer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import redisson.config.tingyu.aop.LockAop; import redisson.config.tingyu.aop.MQAop; import redisson.config.tingyu.operation.RedissonBinary; import redisson.config.tingyu.operation.RedissonCollection; import redisson.config.tingyu.operation.RedissonObject; import redisson.config.tingyu.properties.MultipleServerConfig; import redisson.config.tingyu.properties.RedissonProperties; @Configuration @EnableConfigurationProperties(value = RedissonProperties.class) @ConditionalOnClass(RedissonProperties.class) public class RedissonConfiguration { @Autowired private RedissonProperties redissonProperties; @Bean @ConditionalOnMissingBean(LockAop.class) public LockAop lockAop() { return new LockAop(); } @Bean @ConditionalOnMissingBean(MQAop.class) public MQAop MQAop() { return new MQAop(); } @Bean @ConditionalOnMissingBean(RedissonBinary.class) public RedissonBinary RedissonBinary() { return new RedissonBinary(); } @Bean @ConditionalOnMissingBean(RedissonObject.class) public RedissonObject RedissonObject() { return new RedissonObject(); } @Bean @ConditionalOnMissingBean(RedissonCollection.class) public RedissonCollection RedissonCollection() { return new RedissonCollection(); } @Bean @ConditionalOnMissingBean(RedissonClient.class) public RedissonClient redissonClient() { Config config=new Config(); try { config.setCodec((Codec) Class.forName(redissonProperties.getCodec()).newInstance()); } catch (Exception e) { throw new RuntimeException(e); } config.setTransportMode(redissonProperties.getTransportMode()); if(redissonProperties.getThreads()!=null){ config.setThreads(redissonProperties.getThreads()); } if(redissonProperties.getNettyThreads()!=null){ config.setNettyThreads(redissonProperties.getNettyThreads()); } config.setReferenceEnabled(redissonProperties.getReferenceEnabled()); config.setLockWatchdogTimeout(redissonProperties.getLockWatchdogTimeout()); config.setKeepPubSubOrder(redissonProperties.getKeepPubSubOrder()); config.setDecodeInExecutor(redissonProperties.getDecodeInExecutor()); config.setUseScriptCache(redissonProperties.getUseScriptCache()); config.setMinCleanUpDelay(redissonProperties.getMinCleanUpDelay()); config.setMaxCleanUpDelay(redissonProperties.getMaxCleanUpDelay()); MultipleServerConfig multipleServerConfig = redissonProperties.getMultipleServerConfig(); switch (redissonProperties.getModel()){ case SINGLE: SingleServerConfig singleServerConfig = config.useSingleServer(); // SingleServerConfig param = redissonProperties.getSingleServerConfig(); singleServerConfig.setAddress(prefixAddress("47.104.130.105:6379")); singleServerConfig.setConnectionMinimumIdleSize(32); singleServerConfig.setConnectionPoolSize(64); singleServerConfig.setDatabase(0); singleServerConfig.setDnsMonitoringInterval(5000L); singleServerConfig.setSubscriptionConnectionMinimumIdleSize(1); singleServerConfig.setSubscriptionConnectionPoolSize(50); // singleServerConfig.setPingTimeout(redissonProperties.getPingTimeout()); singleServerConfig.setClientName(redissonProperties.getClientName()); singleServerConfig.setConnectTimeout(redissonProperties.getConnectTimeout()); singleServerConfig.setIdleConnectionTimeout(redissonProperties.getIdleConnectionTimeout()); singleServerConfig.setKeepAlive(redissonProperties.getKeepAlive()); singleServerConfig.setPassword(redissonProperties.getPassword()); singleServerConfig.setPingConnectionInterval(redissonProperties.getPingConnectionInterval()); singleServerConfig.setRetryAttempts(redissonProperties.getRetryAttempts()); singleServerConfig.setRetryInterval(redissonProperties.getRetryInterval()); singleServerConfig.setSslEnableEndpointIdentification(redissonProperties.getSslEnableEndpointIdentification()); // singleServerConfig.setSslKeystore(redissonProperties.getSslKeystore()); singleServerConfig.setSslKeystorePassword(redissonProperties.getSslKeystorePassword()); singleServerConfig.setSslProvider(redissonProperties.getSslProvider()); // singleServerConfig.setSslTruststore(redissonProperties.getSslTruststore()); singleServerConfig.setSslTruststorePassword(redissonProperties.getSslTruststorePassword()); singleServerConfig.setSubscriptionsPerConnection(redissonProperties.getSubscriptionsPerConnection()); singleServerConfig.setTcpNoDelay(redissonProperties.getTcpNoDelay()); singleServerConfig.setTimeout(redissonProperties.getTimeout()); break; case CLUSTER: ClusterServersConfig clusterServersConfig = config.useClusterServers(); clusterServersConfig.setScanInterval(multipleServerConfig.getScanInterval()); clusterServersConfig.setSlaveConnectionMinimumIdleSize(multipleServerConfig.getSlaveConnectionMinimumIdleSize()); clusterServersConfig.setSlaveConnectionPoolSize(multipleServerConfig.getSlaveConnectionPoolSize()); clusterServersConfig.setFailedSlaveReconnectionInterval(multipleServerConfig.getFailedSlaveReconnectionInterval()); clusterServersConfig.setFailedSlaveCheckInterval(multipleServerConfig.getFailedSlaveCheckInterval()); clusterServersConfig.setMasterConnectionMinimumIdleSize(multipleServerConfig.getMasterConnectionMinimumIdleSize()); clusterServersConfig.setMasterConnectionPoolSize(multipleServerConfig.getMasterConnectionPoolSize()); clusterServersConfig.setReadMode(multipleServerConfig.getReadMode()); clusterServersConfig.setSubscriptionMode(multipleServerConfig.getSubscriptionMode()); clusterServersConfig.setSubscriptionConnectionMinimumIdleSize(multipleServerConfig.getSubscriptionConnectionMinimumIdleSize()); clusterServersConfig.setSubscriptionConnectionPoolSize(multipleServerConfig.getSubscriptionConnectionPoolSize()); clusterServersConfig.setDnsMonitoringInterval(multipleServerConfig.getDnsMonitoringInterval()); try { clusterServersConfig.setLoadBalancer((LoadBalancer) Class.forName(multipleServerConfig.getLoadBalancer()).newInstance()); } catch (Exception e) { throw new RuntimeException(e); } for (String nodeAddress : multipleServerConfig.getNodeAddresses()) { clusterServersConfig.addNodeAddress(prefixAddress(nodeAddress)); } // clusterServersConfig.setPingTimeout(redissonProperties.getPingTimeout()); clusterServersConfig.setClientName(redissonProperties.getClientName()); clusterServersConfig.setConnectTimeout(redissonProperties.getConnectTimeout()); clusterServersConfig.setIdleConnectionTimeout(redissonProperties.getIdleConnectionTimeout()); clusterServersConfig.setKeepAlive(redissonProperties.getKeepAlive()); clusterServersConfig.setPassword(redissonProperties.getPassword()); clusterServersConfig.setPingConnectionInterval(redissonProperties.getPingConnectionInterval()); clusterServersConfig.setRetryAttempts(redissonProperties.getRetryAttempts()); clusterServersConfig.setRetryInterval(redissonProperties.getRetryInterval()); clusterServersConfig.setSslEnableEndpointIdentification(redissonProperties.getSslEnableEndpointIdentification()); // clusterServersConfig.setSslKeystore(redissonProperties.getSslKeystore()); clusterServersConfig.setSslKeystorePassword(redissonProperties.getSslKeystorePassword()); clusterServersConfig.setSslProvider(redissonProperties.getSslProvider()); // clusterServersConfig.setSslTruststore(redissonProperties.getSslTruststore()); clusterServersConfig.setSslTruststorePassword(redissonProperties.getSslTruststorePassword()); clusterServersConfig.setSubscriptionsPerConnection(redissonProperties.getSubscriptionsPerConnection()); clusterServersConfig.setTcpNoDelay(redissonProperties.getTcpNoDelay()); clusterServersConfig.setTimeout(redissonProperties.getTimeout()); break; case SENTINEL: SentinelServersConfig sentinelServersConfig = config.useSentinelServers(); sentinelServersConfig.setDatabase(multipleServerConfig.getDatabase()); sentinelServersConfig.setMasterName(multipleServerConfig.getMasterName()); sentinelServersConfig.setScanInterval(multipleServerConfig.getScanInterval()); sentinelServersConfig.setSlaveConnectionMinimumIdleSize(multipleServerConfig.getSlaveConnectionMinimumIdleSize()); sentinelServersConfig.setSlaveConnectionPoolSize(multipleServerConfig.getSlaveConnectionPoolSize()); sentinelServersConfig.setFailedSlaveReconnectionInterval(multipleServerConfig.getFailedSlaveReconnectionInterval()); sentinelServersConfig.setFailedSlaveCheckInterval(multipleServerConfig.getFailedSlaveCheckInterval()); sentinelServersConfig.setMasterConnectionMinimumIdleSize(multipleServerConfig.getMasterConnectionMinimumIdleSize()); sentinelServersConfig.setMasterConnectionPoolSize(multipleServerConfig.getMasterConnectionPoolSize()); sentinelServersConfig.setReadMode(multipleServerConfig.getReadMode()); sentinelServersConfig.setSubscriptionMode(multipleServerConfig.getSubscriptionMode()); sentinelServersConfig.setSubscriptionConnectionMinimumIdleSize(multipleServerConfig.getSubscriptionConnectionMinimumIdleSize()); sentinelServersConfig.setSubscriptionConnectionPoolSize(multipleServerConfig.getSubscriptionConnectionPoolSize()); sentinelServersConfig.setDnsMonitoringInterval(multipleServerConfig.getDnsMonitoringInterval()); try { sentinelServersConfig.setLoadBalancer((LoadBalancer) Class.forName(multipleServerConfig.getLoadBalancer()).newInstance()); } catch (Exception e) { throw new RuntimeException(e); } for (String nodeAddress : multipleServerConfig.getNodeAddresses()) { sentinelServersConfig.addSentinelAddress(prefixAddress(nodeAddress)); } // sentinelServersConfig.setPingTimeout(redissonProperties.getPingTimeout()); sentinelServersConfig.setClientName(redissonProperties.getClientName()); sentinelServersConfig.setConnectTimeout(redissonProperties.getConnectTimeout()); sentinelServersConfig.setIdleConnectionTimeout(redissonProperties.getIdleConnectionTimeout()); sentinelServersConfig.setKeepAlive(redissonProperties.getKeepAlive()); sentinelServersConfig.setPassword(redissonProperties.getPassword()); sentinelServersConfig.setPingConnectionInterval(redissonProperties.getPingConnectionInterval()); sentinelServersConfig.setRetryAttempts(redissonProperties.getRetryAttempts()); sentinelServersConfig.setRetryInterval(redissonProperties.getRetryInterval()); sentinelServersConfig.setSslEnableEndpointIdentification(redissonProperties.getSslEnableEndpointIdentification()); // sentinelServersConfig.setSslKeystore(redissonProperties.getSslKeystore()); sentinelServersConfig.setSslKeystorePassword(redissonProperties.getSslKeystorePassword()); sentinelServersConfig.setSslProvider(redissonProperties.getSslProvider()); // sentinelServersConfig.setSslTruststore(redissonProperties.getSslTruststore()); sentinelServersConfig.setSslTruststorePassword(redissonProperties.getSslTruststorePassword()); sentinelServersConfig.setSubscriptionsPerConnection(redissonProperties.getSubscriptionsPerConnection()); sentinelServersConfig.setTcpNoDelay(redissonProperties.getTcpNoDelay()); sentinelServersConfig.setTimeout(redissonProperties.getTimeout()); break; case REPLICATED: ReplicatedServersConfig replicatedServersConfig = config.useReplicatedServers(); replicatedServersConfig.setDatabase(multipleServerConfig.getDatabase()); replicatedServersConfig.setScanInterval(multipleServerConfig.getScanInterval()); replicatedServersConfig.setSlaveConnectionMinimumIdleSize(multipleServerConfig.getSlaveConnectionMinimumIdleSize()); replicatedServersConfig.setSlaveConnectionPoolSize(multipleServerConfig.getSlaveConnectionPoolSize()); replicatedServersConfig.setFailedSlaveReconnectionInterval(multipleServerConfig.getFailedSlaveReconnectionInterval()); replicatedServersConfig.setFailedSlaveCheckInterval(multipleServerConfig.getFailedSlaveCheckInterval()); replicatedServersConfig.setMasterConnectionMinimumIdleSize(multipleServerConfig.getMasterConnectionMinimumIdleSize()); replicatedServersConfig.setMasterConnectionPoolSize(multipleServerConfig.getMasterConnectionPoolSize()); replicatedServersConfig.setReadMode(multipleServerConfig.getReadMode()); replicatedServersConfig.setSubscriptionMode(multipleServerConfig.getSubscriptionMode()); replicatedServersConfig.setSubscriptionConnectionMinimumIdleSize(multipleServerConfig.getSubscriptionConnectionMinimumIdleSize()); replicatedServersConfig.setSubscriptionConnectionPoolSize(multipleServerConfig.getSubscriptionConnectionPoolSize()); replicatedServersConfig.setDnsMonitoringInterval(multipleServerConfig.getDnsMonitoringInterval()); try { replicatedServersConfig.setLoadBalancer((LoadBalancer) Class.forName(multipleServerConfig.getLoadBalancer()).newInstance()); } catch (Exception e) { throw new RuntimeException(e); } for (String nodeAddress : multipleServerConfig.getNodeAddresses()) { replicatedServersConfig.addNodeAddress(prefixAddress(nodeAddress)); } // replicatedServersConfig.setPingTimeout(redissonProperties.getPingTimeout()); replicatedServersConfig.setClientName(redissonProperties.getClientName()); replicatedServersConfig.setConnectTimeout(redissonProperties.getConnectTimeout()); replicatedServersConfig.setIdleConnectionTimeout(redissonProperties.getIdleConnectionTimeout()); replicatedServersConfig.setKeepAlive(redissonProperties.getKeepAlive()); replicatedServersConfig.setPassword(redissonProperties.getPassword()); replicatedServersConfig.setPingConnectionInterval(redissonProperties.getPingConnectionInterval()); replicatedServersConfig.setRetryAttempts(redissonProperties.getRetryAttempts()); replicatedServersConfig.setRetryInterval(redissonProperties.getRetryInterval()); replicatedServersConfig.setSslEnableEndpointIdentification(redissonProperties.getSslEnableEndpointIdentification()); // replicatedServersConfig.setSslKeystore(redissonProperties.getSslKeystore()); replicatedServersConfig.setSslKeystorePassword(redissonProperties.getSslKeystorePassword()); // replicatedServersConfig.setSslProvider(redissonProperties.getSslProvider()); // replicatedServersConfig.setSslTruststore(redissonProperties.getSslTruststore()); replicatedServersConfig.setSslTruststorePassword(redissonProperties.getSslTruststorePassword()); replicatedServersConfig.setSubscriptionsPerConnection(redissonProperties.getSubscriptionsPerConnection()); replicatedServersConfig.setTcpNoDelay(redissonProperties.getTcpNoDelay()); replicatedServersConfig.setTimeout(redissonProperties.getTimeout()); break; case MASTERSLAVE: MasterSlaveServersConfig masterSlaveServersConfig = config.useMasterSlaveServers(); masterSlaveServersConfig.setDatabase(multipleServerConfig.getDatabase()); masterSlaveServersConfig.setSlaveConnectionMinimumIdleSize(multipleServerConfig.getSlaveConnectionMinimumIdleSize()); masterSlaveServersConfig.setSlaveConnectionPoolSize(multipleServerConfig.getSlaveConnectionPoolSize()); masterSlaveServersConfig.setFailedSlaveReconnectionInterval(multipleServerConfig.getFailedSlaveReconnectionInterval()); masterSlaveServersConfig.setFailedSlaveCheckInterval(multipleServerConfig.getFailedSlaveCheckInterval()); masterSlaveServersConfig.setMasterConnectionMinimumIdleSize(multipleServerConfig.getMasterConnectionMinimumIdleSize()); masterSlaveServersConfig.setMasterConnectionPoolSize(multipleServerConfig.getMasterConnectionPoolSize()); masterSlaveServersConfig.setReadMode(multipleServerConfig.getReadMode()); masterSlaveServersConfig.setSubscriptionMode(multipleServerConfig.getSubscriptionMode()); masterSlaveServersConfig.setSubscriptionConnectionMinimumIdleSize(multipleServerConfig.getSubscriptionConnectionMinimumIdleSize()); masterSlaveServersConfig.setSubscriptionConnectionPoolSize(multipleServerConfig.getSubscriptionConnectionPoolSize()); masterSlaveServersConfig.setDnsMonitoringInterval(multipleServerConfig.getDnsMonitoringInterval()); try { masterSlaveServersConfig.setLoadBalancer((LoadBalancer) Class.forName(multipleServerConfig.getLoadBalancer()).newInstance()); } catch (Exception e) { throw new RuntimeException(e); } int index=0; for (String nodeAddress : multipleServerConfig.getNodeAddresses()) { if(index++==0){ masterSlaveServersConfig.setMasterAddress(prefixAddress(nodeAddress)); }else{ masterSlaveServersConfig.addSlaveAddress(prefixAddress(nodeAddress)); } } // masterSlaveServersConfig.setPingTimeout(redissonProperties.getPingTimeout()); masterSlaveServersConfig.setClientName(redissonProperties.getClientName()); masterSlaveServersConfig.setConnectTimeout(redissonProperties.getConnectTimeout()); masterSlaveServersConfig.setIdleConnectionTimeout(redissonProperties.getIdleConnectionTimeout()); masterSlaveServersConfig.setKeepAlive(redissonProperties.getKeepAlive()); masterSlaveServersConfig.setPassword(redissonProperties.getPassword()); masterSlaveServersConfig.setPingConnectionInterval(redissonProperties.getPingConnectionInterval()); masterSlaveServersConfig.setRetryAttempts(redissonProperties.getRetryAttempts()); masterSlaveServersConfig.setRetryInterval(redissonProperties.getRetryInterval()); masterSlaveServersConfig.setSslEnableEndpointIdentification(redissonProperties.getSslEnableEndpointIdentification()); // masterSlaveServersConfig.setSslKeystore(redissonProperties.getSslKeystore()); masterSlaveServersConfig.setSslKeystorePassword(redissonProperties.getSslKeystorePassword()); masterSlaveServersConfig.setSslProvider(redissonProperties.getSslProvider()); // masterSlaveServersConfig.setSslTruststore(redissonProperties.getSslTruststore()); masterSlaveServersConfig.setSslTruststorePassword(redissonProperties.getSslTruststorePassword()); masterSlaveServersConfig.setSubscriptionsPerConnection(redissonProperties.getSubscriptionsPerConnection()); masterSlaveServersConfig.setTcpNoDelay(redissonProperties.getTcpNoDelay()); masterSlaveServersConfig.setTimeout(redissonProperties.getTimeout()); break; } return Redisson.create(config); } private String prefixAddress(String address){ if(!StringUtils.isEmpty(address)&&!address.startsWith("redis")){ return "redis://"+address; } return address; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/configuration/MQConfiguration.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/configuration/MQConfiguration.java
package redisson.config.tingyu.configuration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redisson.config.tingyu.mq.RedissonMQListener; /** * MQ配置 */ @Configuration public class MQConfiguration { @Bean @ConditionalOnMissingBean(RedissonMQListener.class) public RedissonMQListener RedissonMQListener() { return new RedissonMQListener(); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/operation/RedissonBinary.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/operation/RedissonBinary.java
package redisson.config.tingyu.operation; import org.redisson.api.RBinaryStream; import org.redisson.api.RListMultimap; import org.redisson.api.RedissonClient; import javax.annotation.Resource; import java.io.InputStream; import java.io.OutputStream; /** * 操作对象二进制 */ public class RedissonBinary { @Resource private RedissonClient redissonClient; /** * 获取输出流 * @param name * @return */ public OutputStream getOutputStream(String name) { RListMultimap<Object, Object> listMultimap = redissonClient.getListMultimap(""); RBinaryStream binaryStream = redissonClient.getBinaryStream(name); return binaryStream.getOutputStream(); } /** * 获取输入流 * @param name * @return */ public InputStream getInputStream(String name) { RBinaryStream binaryStream = redissonClient.getBinaryStream(name); return binaryStream.getInputStream(); } /** * 获取输入流 * @param name * @return */ public InputStream getValue(String name,OutputStream stream) { try { RBinaryStream binaryStream = redissonClient.getBinaryStream(name); InputStream inputStream = binaryStream.getInputStream(); byte[] buff=new byte[1024]; int len; while ((len=inputStream.read(buff))!=-1){ stream.write(buff,0,len); } return binaryStream.getInputStream(); } catch (Exception e) { throw new RuntimeException(e); } } /** * 获取对象空间 * * @param name * @return */ public RBinaryStream getBucket(String name) { return redissonClient.getBinaryStream(name); } /** * 设置对象的值 * * @param name 键 * @param value 值 * @return */ public void setValue(String name, InputStream value) { try { RBinaryStream binaryStream = redissonClient.getBinaryStream(name); binaryStream.delete(); OutputStream outputStream = binaryStream.getOutputStream(); byte[] buff = new byte[1024]; int len; while ((len=value.read(buff))!=-1){ outputStream.write(buff,0,len); } } catch (Exception e) { throw new RuntimeException(e); } } /** * 删除对象 * * @param name 键 * @return true 删除成功,false 不成功 */ public Boolean delete(String name) { RBinaryStream binaryStream = redissonClient.getBinaryStream(name); return binaryStream.delete(); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/operation/RedissonObject.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/operation/RedissonObject.java
package redisson.config.tingyu.operation; import org.redisson.api.RBucket; import org.redisson.api.RedissonClient; import redisson.config.tingyu.properties.RedissonProperties; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; /** * 操作对象 */ public class RedissonObject { @Resource private RedissonClient redissonClient; @Resource private RedissonProperties redissonProperties; /** * 获取对象值 * * @param name * @param <T> * @return */ public <T> T getValue(String name) { RBucket<T> bucket = redissonClient.getBucket(name); return bucket.get(); } /** * 获取对象空间 * * @param name * @param <T> * @return */ public <T> RBucket<T> getBucket(String name) { return redissonClient.getBucket(name); } /** * 设置对象的值 * * @param name 键 * @param value 值 * @return */ public <T> void setValue(String name, T value) { setValue(name,value,redissonProperties.getDataValidTime()); } /** * 设置对象的值 * * @param name 键 * @param value 值 * @param time 缓存时间 单位毫秒 -1 永久缓存 * @return */ public <T> void setValue(String name, T value, Long time) { RBucket<Object> bucket = redissonClient.getBucket(name); if(time==-1){ bucket.set(value); }else { bucket.set(value, time, TimeUnit.MILLISECONDS); } } /** * 如果值已经存在则则不设置 * * @param name 键 * @param value 值 * @param time 缓存时间 单位毫秒 * @return true 设置成功,false 值存在,不设置 */ public <T> Boolean trySetValue(String name, T value, Long time) { RBucket<Object> bucket = redissonClient.getBucket(name); boolean b; if(time==-1){ b = bucket.trySet(value); }else { b = bucket.trySet(value, time, TimeUnit.MILLISECONDS); } return b; } /** * 如果值已经存在则则不设置 * * @param name 键 * @param value 值 * @return true 设置成功,false 值存在,不设置 */ public <T> Boolean trySetValue(String name, T value) { return trySetValue(name,value,redissonProperties.getDataValidTime()); } /** * 删除对象 * * @param name 键 * @return true 删除成功,false 不成功 */ public Boolean delete(String name) { return redissonClient.getBucket(name).delete(); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/operation/RedissonCollection.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/operation/RedissonCollection.java
package redisson.config.tingyu.operation; import org.redisson.api.RList; import org.redisson.api.RMap; import org.redisson.api.RSet; import org.redisson.api.RedissonClient; import redisson.config.tingyu.properties.RedissonProperties; import javax.annotation.Resource; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * 操作集合 */ public class RedissonCollection { @Resource private RedissonClient redissonClient; @Resource private RedissonProperties redissonProperties; /** * 获取map集合 * @param name * @param <K> * @param <V> * @return */ public <K,V> RMap<K, V> getMap(String name){ return redissonClient.getMap(name); } /** * 设置map集合 * @param name * @param data * @param time 缓存时间,单位毫秒 -1永久缓存 * @return */ public void setMapValues(String name, Map data,Long time){ RMap map = redissonClient.getMap(name); Long dataValidTime = redissonProperties.getDataValidTime(); if(time!=-1){ map.expire(dataValidTime, TimeUnit.MILLISECONDS); } map.putAll(data); } /** * 设置map集合 * @param name * @param data * @return */ public void setMapValues(String name, Map data){ setMapValues(name,data,redissonProperties.getDataValidTime()); } /** * 获取List集合 * @param name * @return */ public <T> RList<T> getList(String name){ return redissonClient.getList(name); } /** * 设置List集合 * @param name * @param data * @param time 缓存时间,单位毫秒 -1永久缓存 * @return */ public void setListValues(String name, List data, Long time){ RList list = redissonClient.getList(name); Long dataValidTime = redissonProperties.getDataValidTime(); if(time!=-1){ list.expire(dataValidTime, TimeUnit.MILLISECONDS); } list.addAll(data); } /** * 设置List集合 * @param name * @param data * @return */ public void setListValues(String name, List data){ setListValues(name,data,redissonProperties.getDataValidTime()); } /** * 获取set集合 * @param name * @return */ public <T> RSet<T> getSet(String name){ return redissonClient.getSet(name); } /** * 设置set集合 * @param name * @param data * @param time 缓存时间,单位毫秒 -1永久缓存 * @return */ public void setSetValues(String name, Set data, Long time){ RSet set = redissonClient.getSet(name); Long dataValidTime = redissonProperties.getDataValidTime(); if(time!=-1){ set.expire(dataValidTime, TimeUnit.MILLISECONDS); } set.addAll(data); } /** * 设置set集合 * @param name * @param data * @return */ public void setSetValues(String name, Set data){ setSetValues(name,data,redissonProperties.getDataValidTime()); } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/properties/RedissonProperties.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/properties/RedissonProperties.java
package redisson.config.tingyu.properties; import org.redisson.config.SslProvider; import org.redisson.config.TransportMode; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import redisson.config.tingyu.enums.LockModel; import redisson.config.tingyu.enums.Model; import java.net.URI; @ConfigurationProperties(prefix = "redisson") public class RedissonProperties { private Model model=Model.SINGLE; private String codec="org.redisson.codec.JsonJacksonCodec"; private Integer threads; private Integer nettyThreads; private TransportMode transportMode= TransportMode.NIO; //公共参数 private Integer idleConnectionTimeout = 10000; private Integer pingTimeout = 1000; private Integer connectTimeout = 10000; private Integer timeout = 3000; private Integer retryAttempts = 3; private Integer retryInterval = 1500; private String password = "123456"; private Integer subscriptionsPerConnection = 5; private String clientName; private Boolean sslEnableEndpointIdentification = true; private SslProvider sslProvider= SslProvider.JDK; private URI sslTruststore; private String sslTruststorePassword; private URI sslKeystore; private String sslKeystorePassword; private Integer pingConnectionInterval=0; private Boolean keepAlive=false; private Boolean tcpNoDelay=false; private Boolean referenceEnabled = true; private Long lockWatchdogTimeout=30000L; private Boolean keepPubSubOrder=true; private Boolean decodeInExecutor=false; private Boolean useScriptCache=false; private Integer minCleanUpDelay=5; private Integer maxCleanUpDelay=1800; //锁的模式 如果不设置 单个key默认可重入锁 多个key默认联锁 private LockModel lockModel; //等待加锁超时时间 -1一直等待 private Long attemptTimeout= 10000L; //数据缓存时间 默认30分钟 private Long dataValidTime=1000*60* 30L; //结束 @NestedConfigurationProperty private SingleServerConfig singleServerConfig; @NestedConfigurationProperty private MultipleServerConfig multipleServerConfig; public Long getDataValidTime() { return dataValidTime; } public void setDataValidTime(Long dataValidTime) { this.dataValidTime = dataValidTime; } public LockModel getLockModel() { return lockModel; } public void setLockModel(LockModel lockModel) { this.lockModel = lockModel; } public Long getAttemptTimeout() { return attemptTimeout; } public void setAttemptTimeout(Long attemptTimeout) { this.attemptTimeout = attemptTimeout; } public Boolean getReferenceEnabled() { return referenceEnabled; } public void setReferenceEnabled(Boolean referenceEnabled) { this.referenceEnabled = referenceEnabled; } public Long getLockWatchdogTimeout() { return lockWatchdogTimeout; } public void setLockWatchdogTimeout(Long lockWatchdogTimeout) { this.lockWatchdogTimeout = lockWatchdogTimeout; } public Boolean getKeepPubSubOrder() { return keepPubSubOrder; } public void setKeepPubSubOrder(Boolean keepPubSubOrder) { this.keepPubSubOrder = keepPubSubOrder; } public Boolean getDecodeInExecutor() { return decodeInExecutor; } public void setDecodeInExecutor(Boolean decodeInExecutor) { this.decodeInExecutor = decodeInExecutor; } public Boolean getUseScriptCache() { return useScriptCache; } public void setUseScriptCache(Boolean useScriptCache) { this.useScriptCache = useScriptCache; } public Integer getMinCleanUpDelay() { return minCleanUpDelay; } public void setMinCleanUpDelay(Integer minCleanUpDelay) { this.minCleanUpDelay = minCleanUpDelay; } public Integer getMaxCleanUpDelay() { return maxCleanUpDelay; } public void setMaxCleanUpDelay(Integer maxCleanUpDelay) { this.maxCleanUpDelay = maxCleanUpDelay; } public Model getModel() { return model; } public void setModel(Model model) { this.model = model; } public SingleServerConfig getSingleServerConfig() { return singleServerConfig; } public void setSingleServerConfig(SingleServerConfig singleServerConfig) { this.singleServerConfig = singleServerConfig; } public MultipleServerConfig getMultipleServerConfig() { return multipleServerConfig; } public void setMultipleServerConfig(MultipleServerConfig multipleServerConfig) { this.multipleServerConfig = multipleServerConfig; } public void setIdleConnectionTimeout(Integer idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; } public void setPingTimeout(Integer pingTimeout) { this.pingTimeout = pingTimeout; } public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } public void setTimeout(Integer timeout) { this.timeout = timeout; } public void setRetryAttempts(Integer retryAttempts) { this.retryAttempts = retryAttempts; } public void setRetryInterval(Integer retryInterval) { this.retryInterval = retryInterval; } public void setSubscriptionsPerConnection(Integer subscriptionsPerConnection) { this.subscriptionsPerConnection = subscriptionsPerConnection; } public Boolean getSslEnableEndpointIdentification() { return sslEnableEndpointIdentification; } public void setSslEnableEndpointIdentification(Boolean sslEnableEndpointIdentification) { this.sslEnableEndpointIdentification = sslEnableEndpointIdentification; } public void setPingConnectionInterval(Integer pingConnectionInterval) { this.pingConnectionInterval = pingConnectionInterval; } public Boolean getKeepAlive() { return keepAlive; } public void setKeepAlive(Boolean keepAlive) { this.keepAlive = keepAlive; } public Boolean getTcpNoDelay() { return tcpNoDelay; } public void setTcpNoDelay(Boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } public Integer getThreads() { return threads; } public void setThreads(Integer threads) { this.threads = threads; } public Integer getNettyThreads() { return nettyThreads; } public void setNettyThreads(Integer nettyThreads) { this.nettyThreads = nettyThreads; } public TransportMode getTransportMode() { return transportMode; } public void setTransportMode(TransportMode transportMode) { this.transportMode = transportMode; } public String getCodec() { return codec; } public void setCodec(String codec) { this.codec = codec; } public int getIdleConnectionTimeout() { return idleConnectionTimeout; } public void setIdleConnectionTimeout(int idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; } public int getPingTimeout() { return pingTimeout; } public void setPingTimeout(int pingTimeout) { this.pingTimeout = pingTimeout; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public int getRetryAttempts() { return retryAttempts; } public void setRetryAttempts(int retryAttempts) { this.retryAttempts = retryAttempts; } public int getRetryInterval() { return retryInterval; } public void setRetryInterval(int retryInterval) { this.retryInterval = retryInterval; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getSubscriptionsPerConnection() { return subscriptionsPerConnection; } public void setSubscriptionsPerConnection(int subscriptionsPerConnection) { this.subscriptionsPerConnection = subscriptionsPerConnection; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public boolean isSslEnableEndpointIdentification() { return sslEnableEndpointIdentification; } public void setSslEnableEndpointIdentification(boolean sslEnableEndpointIdentification) { this.sslEnableEndpointIdentification = sslEnableEndpointIdentification; } public SslProvider getSslProvider() { return sslProvider; } public void setSslProvider(SslProvider sslProvider) { this.sslProvider = sslProvider; } public URI getSslTruststore() { return sslTruststore; } public void setSslTruststore(URI sslTruststore) { this.sslTruststore = sslTruststore; } public String getSslTruststorePassword() { return sslTruststorePassword; } public void setSslTruststorePassword(String sslTruststorePassword) { this.sslTruststorePassword = sslTruststorePassword; } public URI getSslKeystore() { return sslKeystore; } public void setSslKeystore(URI sslKeystore) { this.sslKeystore = sslKeystore; } public String getSslKeystorePassword() { return sslKeystorePassword; } public void setSslKeystorePassword(String sslKeystorePassword) { this.sslKeystorePassword = sslKeystorePassword; } public int getPingConnectionInterval() { return pingConnectionInterval; } public void setPingConnectionInterval(int pingConnectionInterval) { this.pingConnectionInterval = pingConnectionInterval; } public boolean isKeepAlive() { return keepAlive; } public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; } public boolean isTcpNoDelay() { return tcpNoDelay; } public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/properties/MultipleServerConfig.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/properties/MultipleServerConfig.java
package redisson.config.tingyu.properties; import org.redisson.config.ReadMode; import org.redisson.config.SubscriptionMode; import java.util.ArrayList; import java.util.List; /** * 多节点配置 */ public class MultipleServerConfig { private String loadBalancer = "org.redisson.connection.balancer.RoundRobinLoadBalancer"; private Integer slaveConnectionMinimumIdleSize = 32; private Integer slaveConnectionPoolSize = 64; private Integer failedSlaveReconnectionInterval = 3000; private Integer failedSlaveCheckInterval = 180000; private Integer masterConnectionMinimumIdleSize = 32; private Integer masterConnectionPoolSize = 64; private ReadMode readMode= ReadMode.SLAVE; private SubscriptionMode subscriptionMode= SubscriptionMode.SLAVE; private Integer subscriptionConnectionMinimumIdleSize=1; private Integer subscriptionConnectionPoolSize=50; private Long dnsMonitoringInterval=5000L; private List<String> nodeAddresses = new ArrayList(); //集群,哨兵,云托管 private Integer scanInterval = 1000; //哨兵模式,云托管,主从 private Integer database = 0; //哨兵模式 private String masterName; public String getMasterName() { return masterName; } public void setMasterName(String masterName) { this.masterName = masterName; } public String getLoadBalancer() { return loadBalancer; } public void setLoadBalancer(String loadBalancer) { this.loadBalancer = loadBalancer; } public Integer getSlaveConnectionMinimumIdleSize() { return slaveConnectionMinimumIdleSize; } public Integer getSlaveConnectionPoolSize() { return slaveConnectionPoolSize; } public Integer getFailedSlaveReconnectionInterval() { return failedSlaveReconnectionInterval; } public Integer getFailedSlaveCheckInterval() { return failedSlaveCheckInterval; } public Integer getMasterConnectionMinimumIdleSize() { return masterConnectionMinimumIdleSize; } public Integer getMasterConnectionPoolSize() { return masterConnectionPoolSize; } public ReadMode getReadMode() { return readMode; } public SubscriptionMode getSubscriptionMode() { return subscriptionMode; } public Integer getSubscriptionConnectionMinimumIdleSize() { return subscriptionConnectionMinimumIdleSize; } public Integer getSubscriptionConnectionPoolSize() { return subscriptionConnectionPoolSize; } public Long getDnsMonitoringInterval() { return dnsMonitoringInterval; } public List<String> getNodeAddresses() { return nodeAddresses; } public void setNodeAddresses(List<String> nodeAddresses) { this.nodeAddresses = nodeAddresses; } public Integer getScanInterval() { return scanInterval; } public void setScanInterval(Integer scanInterval) { this.scanInterval = scanInterval; } public Integer getDatabase() { return database; } public void setDatabase(Integer database) { this.database = database; } public void setSlaveConnectionMinimumIdleSize(Integer slaveConnectionMinimumIdleSize) { this.slaveConnectionMinimumIdleSize = slaveConnectionMinimumIdleSize; } public void setSlaveConnectionPoolSize(Integer slaveConnectionPoolSize) { this.slaveConnectionPoolSize = slaveConnectionPoolSize; } public void setFailedSlaveReconnectionInterval(Integer failedSlaveReconnectionInterval) { this.failedSlaveReconnectionInterval = failedSlaveReconnectionInterval; } public void setFailedSlaveCheckInterval(Integer failedSlaveCheckInterval) { this.failedSlaveCheckInterval = failedSlaveCheckInterval; } public void setMasterConnectionMinimumIdleSize(Integer masterConnectionMinimumIdleSize) { this.masterConnectionMinimumIdleSize = masterConnectionMinimumIdleSize; } public void setMasterConnectionPoolSize(Integer masterConnectionPoolSize) { this.masterConnectionPoolSize = masterConnectionPoolSize; } public void setReadMode(ReadMode readMode) { this.readMode = readMode; } public void setSubscriptionMode(SubscriptionMode subscriptionMode) { this.subscriptionMode = subscriptionMode; } public void setSubscriptionConnectionMinimumIdleSize(Integer subscriptionConnectionMinimumIdleSize) { this.subscriptionConnectionMinimumIdleSize = subscriptionConnectionMinimumIdleSize; } public void setSubscriptionConnectionPoolSize(Integer subscriptionConnectionPoolSize) { this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize; } public void setDnsMonitoringInterval(Long dnsMonitoringInterval) { this.dnsMonitoringInterval = dnsMonitoringInterval; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/properties/SingleServerConfig.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/properties/SingleServerConfig.java
package redisson.config.tingyu.properties; /** * 单节点配置 */ public class SingleServerConfig { private String address = "47.104.130.105:6379"; private Integer subscriptionConnectionMinimumIdleSize = 1; private Integer subscriptionConnectionPoolSize = 50; private Integer connectionMinimumIdleSize = 32; private Integer connectionPoolSize = 64; private Integer database = 0; private Long dnsMonitoringInterval = 5000L; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getSubscriptionConnectionMinimumIdleSize() { return subscriptionConnectionMinimumIdleSize; } public void setSubscriptionConnectionMinimumIdleSize(Integer subscriptionConnectionMinimumIdleSize) { this.subscriptionConnectionMinimumIdleSize = subscriptionConnectionMinimumIdleSize; } public Integer getSubscriptionConnectionPoolSize() { return subscriptionConnectionPoolSize; } public void setSubscriptionConnectionPoolSize(Integer subscriptionConnectionPoolSize) { this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize; } public Integer getConnectionMinimumIdleSize() { return connectionMinimumIdleSize; } public void setConnectionMinimumIdleSize(Integer connectionMinimumIdleSize) { this.connectionMinimumIdleSize = connectionMinimumIdleSize; } public Integer getConnectionPoolSize() { return connectionPoolSize; } public void setConnectionPoolSize(Integer connectionPoolSize) { this.connectionPoolSize = connectionPoolSize; } public Integer getDatabase() { return database; } public void setDatabase(Integer database) { this.database = database; } public Long getDnsMonitoringInterval() { return dnsMonitoringInterval; } public void setDnsMonitoringInterval(Long dnsMonitoringInterval) { this.dnsMonitoringInterval = dnsMonitoringInterval; } }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/Lock.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/Lock.java
package redisson.config.tingyu.annotation; import redisson.config.tingyu.enums.LockModel; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Lock { /** * 锁的模式:如果不设置,自动模式,当参数只有一个.使用 REENTRANT 参数多个 MULTIPLE */ LockModel lockModel() default LockModel.AUTO; /** * 如果keys有多个,如果不设置,则使用 联锁 * @return */ String[] keys() default {}; /** * key的静态常量:当key的spel的值是LIST,数组时使用+号连接将会被spel认为这个变量是个字符串,只能产生一把锁,达不到我们的目的,<br /> * 而我们如果又需要一个常量的话.这个参数将会在拼接在每个元素的后面 * @return */ String keyConstant() default ""; /** * 锁超时时间,默认30000毫秒(可在配置文件全局设置) * @return */ long lockWatchdogTimeout() default 0; /** * 等待加锁超时时间,默认10000毫秒 -1 则表示一直等待(可在配置文件全局设置) * @return */ long attemptTimeout() default 0; }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/EnableCache.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/EnableCache.java
package redisson.config.tingyu.annotation; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import redisson.config.tingyu.configuration.CacheConfiguration; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ java.lang.annotation.ElementType.TYPE }) @Documented @Import(CacheConfiguration.class) @Configuration public @interface EnableCache { /** * 缓存的名称 @Cacheable,@CachePut,@CacheEvict的value必须包含在这里面 * @return */ String[] value(); /** * 缓存时间 默认30分钟 * @return */ long ttl() default 1000*60* 30L; /** * 最长空闲时间 默认30分钟 * @return */ long maxIdleTime() default 1000*60* 30L; }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/MQListener.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/MQListener.java
package redisson.config.tingyu.annotation; import redisson.config.tingyu.enums.MQModel; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MQListener { /** * topic name * @return */ String name(); /** * 匹配模式 <br /> * PRECISE精准的匹配 如:name="myTopic" 那么发送者的topic name也一定要等于myTopic <br /> * PATTERN模糊匹配 如: name="myTopic.*" 那么发送者的topic name 可以是 myTopic.name1 myTopic.name2.尾缀不限定 * @return */ MQModel model() default MQModel.PRECISE; }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/EnableMQ.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/EnableMQ.java
package redisson.config.tingyu.annotation; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import redisson.config.tingyu.configuration.MQConfiguration; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ java.lang.annotation.ElementType.TYPE }) @Documented @Import(MQConfiguration.class) @Configuration public @interface EnableMQ { }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false
tingyunote/Tingyu-Notes
https://github.com/tingyunote/Tingyu-Notes/blob/90219bf94419903f51dac66dd0e13038aa10943d/分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/MQPublish.java
分布式锁redisson多节点+附加源码和压测脚本/redisson.tingyu/src/main/java/redisson/config/tingyu/annotation/MQPublish.java
package redisson.config.tingyu.annotation; import java.lang.annotation.*; /** * MQ发送消息注解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MQPublish { /** * topic name * @return */ String name(); }
java
Apache-2.0
90219bf94419903f51dac66dd0e13038aa10943d
2026-01-05T02:42:38.324015Z
false