xuhy
2026-02-26 b06dab478b1d23a8961facbefed4d4ad88276c67
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package com.xiaopeng.pushMessage.utils;
 
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.push20160801.models.*;
import com.aliyun.sdk.service.push20160801.*;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
 
//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.util.concurrent.CompletableFuture;
 
@Slf4j
public class AliPushUtil {
 
    @Value("${ali.push.accessKeyId}")
    private String accessKeyId;
    @Value("${ali.push.accessKeySecret}")
    private String accessKeySecret;
    @Value("${ali.push.regionId}")
    private String regionId;
    @Value("${ali.push.appKey}")
    private Long appKey;
    @Value("${ali.push.iosAppKey}")
    private Long iosAppKey;
    /**
     * 消息类型  MESSAGE 消息  NOTICE  通知
     */
    private final String PUSH_TYPE = "MESSAGE";
    /**
     * 设备类型 ALL 全部 HARMONY 鸿蒙  IOS ios设备 ANDROID 安卓设备
     */
    private final String DEVICE_TYPE_ALL = "ALL";
    private final String DEVICE_TYPE_HARMONY = "HARMONY";
    private final String DEVICE_TYPE_IOS = "IOS";
    private final String DEVICE_TYPE_ANDROID = "ANDROID";
    /**
     * 推送目标
     * DEVICE:根据设备推送。
     * ACCOUNT:根据账号推送。
     * ALIAS:根据别名推送。
     * TAG:根据标签推送。
     * ALL:推送给全部设备(同一种 DeviceType 的两次全推的间隔至少为 1 秒)。
     */
    private final String TARGET = "ACCOUNT";
 
 
    /**
     *
     * @param account 运维手机号
     * @param title 标题
     * @param body 消息内容
     * @throws Exception
     */
    public String pushMessage(Integer deviceType,String account, String title, String body) throws Exception {
 
        StaticCredentialProvider credentialProvider = StaticCredentialProvider.create(
                Credential.builder()
                        .accessKeyId(accessKeyId)
                        .accessKeySecret(accessKeySecret)
                        .build()
        );
 
        // Configure the Client
        try (AsyncClient client = AsyncClient.builder()
                .region(regionId) // Region ID
                .credentialsProvider(credentialProvider)
                .overrideConfiguration(
                    ClientOverrideConfiguration.create()
                    .setEndpointOverride("cloudpush.aliyuncs.com")
                )
                .build()) {
 
            // 判断账号类型
            Long appKeys = appKey;
            if(deviceType == 2){
                appKeys = iosAppKey;
            }
 
            PushRequest pushRequest = PushRequest.builder()
                    .appKey(appKeys)
                    .pushType(PUSH_TYPE)
                    .deviceType(DEVICE_TYPE_ALL)
                    .target(TARGET)
                    .targetValue(account)
                    .title(title)
                    .body(body)
                    .build();
            CompletableFuture<PushResponse> response = client.push(pushRequest);
            PushResponse resp = response.get();
            String json = new Gson().toJson(resp);
            log.info("运维APP-消息推送:{}",json);
 
            JSONObject jsonObject = JSONObject.parseObject(json);
 
            Integer statusCode = jsonObject.getInteger("statusCode");
            if(statusCode == 200){
                log.info("运维APP-消息推送成功");
                JSONObject resultBody = jsonObject.getJSONObject("body");
                return resultBody.getString("messageId");
            }else{
                log.info("运维APP-消息推送失败");
                return null;
            }
        }
    }
 
    public static void main(String[] args) throws Exception {
 
        // HttpClient Configuration
        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
                .maxConnections(128) // Set the connection pool size
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
                // Configure the proxy
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/
 
        // Configure Credentials authentication information
        StaticCredentialProvider credentialProvider = StaticCredentialProvider.create(
                Credential.builder()
                        .accessKeyId("LTAI5tRNNQCCPn6Hc42RJYLj")
                        .accessKeySecret("5b9sMu7b5Ab87e3Oa1qujQsBXwvjFx")
                        .build()
        );
 
        // Configure the Client
        try (AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(credentialProvider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Push
                                .setEndpointOverride("cloudpush.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build()) {
 
            // Parameter settings for API request
            PushRequest pushRequest = PushRequest.builder()
                    .appKey(335666344L)
                    .pushType("MESSAGE")
                    .deviceType("ALL")
                    .target("ACCOUNT")
                    .targetValue("account1")
                    .title("消息通知")
                    .body("测试")
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();
 
            // Asynchronously get the return value of the API request
            CompletableFuture<PushResponse> response = client.push(pushRequest);
            // Synchronously get the return value of the API request
            PushResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            // Asynchronous processing of return values
            /*response.thenAccept(resp -> {
                System.out.println(new Gson().toJson(resp));
            }).exceptionally(throwable -> { // Handling exceptions
                System.out.println(throwable.getMessage());
                return null;
            });*/
 
        }
    }
 
}