AppConfiguration.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. package com.adx.tencent;
  2. import com.adx.tencent.baidu.AdxClient;
  3. import com.adx.tencent.baidu.AuctionPriceEncoder;
  4. import com.adx.tencent.baidu.ConversionClient;
  5. import com.adx.tencent.config.AppProperties;
  6. import com.adx.tencent.conversionsync.ConversionSyncRunner;
  7. import com.adx.tencent.conversionsync.ConversionSyncService;
  8. import com.adx.tencent.conversionsync.RetryService;
  9. import com.adx.tencent.httpapi.MediaPlacement;
  10. import com.adx.tencent.leader.LeaderElection;
  11. import com.adx.tencent.tagsync.TagEventResolver;
  12. import com.adx.tencent.tagsync.TagEventSyncService;
  13. import com.adx.tencent.tencent.TencentClient;
  14. import com.adx.tencent.storage.RedisHotStore;
  15. import com.adx.tencent.storage.RedisLock;
  16. import com.adx.tencent.storage.TiDBColdStore;
  17. import com.adx.tencent.worker.ColdWorker;
  18. import com.fasterxml.jackson.databind.ObjectMapper;
  19. import org.apache.ibatis.session.SqlSessionFactory;
  20. import org.mybatis.spring.SqlSessionFactoryBean;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. import org.springframework.beans.factory.annotation.Autowired;
  24. import org.springframework.boot.ApplicationArguments;
  25. import org.springframework.boot.ApplicationRunner;
  26. import org.springframework.context.annotation.Bean;
  27. import org.springframework.context.annotation.Configuration;
  28. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  29. import org.springframework.data.redis.connection.RedisConnectionFactory;
  30. import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
  31. import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
  32. import org.springframework.data.redis.core.StringRedisTemplate;
  33. import org.springframework.stereotype.Component;
  34. import org.springframework.scheduling.annotation.Scheduled;
  35. import org.springframework.lang.Nullable;
  36. import javax.sql.DataSource;
  37. import java.time.Duration;
  38. import java.util.HashMap;
  39. import java.util.List;
  40. import java.util.Map;
  41. import java.util.concurrent.ExecutorService;
  42. import java.util.concurrent.Executors;
  43. import java.util.concurrent.atomic.AtomicBoolean;
  44. /**
  45. * 腾讯-百度回传项目 Bean 组装配置类。
  46. * 负责所有核心 Bean 的创建和后台任务(Worker、Leader 选举、定时同步等)。
  47. */
  48. @Configuration
  49. public class AppConfiguration {
  50. private static final Logger log = LoggerFactory.getLogger(AppConfiguration.class);
  51. @Autowired private AppProperties props;
  52. // ─── Redis ───────────────────────────────────────────────────────────────
  53. @Bean
  54. public RedisConnectionFactory redisConnectionFactory() {
  55. String addr = props.getRedisAddr();
  56. String[] parts = addr.split(":", 2);
  57. String host = parts[0];
  58. int port = parts.length > 1 ? Integer.parseInt(parts[1]) : 6379;
  59. RedisStandaloneConfiguration cfg = new RedisStandaloneConfiguration(host, port);
  60. cfg.setDatabase(props.getRedisDb());
  61. if (props.getRedisUsername() != null && !props.getRedisUsername().isBlank()) {
  62. cfg.setUsername(props.getRedisUsername());
  63. }
  64. if (props.getRedisPassword() != null && !props.getRedisPassword().isBlank()) {
  65. cfg.setPassword(props.getRedisPassword());
  66. }
  67. return new LettuceConnectionFactory(cfg);
  68. }
  69. @Bean
  70. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
  71. return new StringRedisTemplate(factory);
  72. }
  73. @Bean
  74. public RedisHotStore redisHotStore(StringRedisTemplate redis, ObjectMapper objectMapper) {
  75. return new RedisHotStore(redis, objectMapper,
  76. tiDBColdStore(objectMapper),
  77. "adx:tencent:",
  78. props.getRedisStream(),
  79. props.getBidTtl());
  80. }
  81. @Bean
  82. public RedisLock redisLock(StringRedisTemplate redis) {
  83. return new RedisLock(redis);
  84. }
  85. @Bean
  86. public LeaderElection leaderElection(RedisLock redisLock) {
  87. return new LeaderElection(redisLock);
  88. }
  89. // ─── TiDB(可选)────────────────────────────────────────────────────────
  90. @Bean
  91. public TiDBColdStore tiDBColdStore(ObjectMapper objectMapper) {
  92. String url = props.getTidbUrl();
  93. if (url == null || url.isBlank()) {
  94. log.info("TiDB URL is empty; cold storage disabled");
  95. return null;
  96. }
  97. try {
  98. DataSource ds = createDataSource(url, props.getTidbUsername(), props.getTidbPassword());
  99. SqlSessionFactory sqlSessionFactory = createSqlSessionFactory(ds);
  100. TiDBColdStore store = new TiDBColdStore(sqlSessionFactory, objectMapper);
  101. store.migrate();
  102. log.info("TiDB cold store initialized and migrated");
  103. return store;
  104. } catch (Exception e) {
  105. log.warn("Failed to open TiDB: {}; cold storage disabled", e.getMessage(), e);
  106. return null;
  107. }
  108. }
  109. private SqlSessionFactory createSqlSessionFactory(DataSource dataSource) throws Exception {
  110. SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  111. factoryBean.setDataSource(dataSource);
  112. factoryBean.setMapperLocations(
  113. new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
  114. return factoryBean.getObject();
  115. }
  116. private DataSource createDataSource(String jdbcUrl, String username, String password) {
  117. org.springframework.jdbc.datasource.DriverManagerDataSource ds =
  118. new org.springframework.jdbc.datasource.DriverManagerDataSource();
  119. ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
  120. ds.setUrl(jdbcUrl);
  121. if (username != null && !username.isBlank()) ds.setUsername(username);
  122. if (password != null && !password.isBlank()) ds.setPassword(password);
  123. return ds;
  124. }
  125. // ─── Baidu 客户端 ────────────────────────────────────────────────────────
  126. @Bean
  127. public AuctionPriceEncoder auctionPriceEncoder() {
  128. return AuctionPriceEncoder.create(
  129. props.getBaiduAuctionPriceEncryption(),
  130. props.getBaiduAuctionPriceEKey(),
  131. props.getBaiduAuctionPriceIKey());
  132. }
  133. @Bean
  134. public AdxClient adxClient(AuctionPriceEncoder encoder, ObjectMapper objectMapper) {
  135. return new AdxClient(props.getBaiduAdxEndpoint(), encoder, objectMapper);
  136. }
  137. @Bean
  138. public ConversionClient conversionClient(ObjectMapper objectMapper) {
  139. return new ConversionClient(
  140. props.getBaiduConversionBaseUrl(),
  141. props.getBaiduCustomerName(),
  142. props.getBaiduSecret(),
  143. objectMapper);
  144. }
  145. // ─── Tencent 客户端 + Sync 服务 ──────────────────────────────────────────
  146. @Bean
  147. public TencentClient tencentClient(ObjectMapper objectMapper, StringRedisTemplate redisTemplate) {
  148. // token 从 Redis 动态获取,支持外部刷新
  149. String tokenRedisKey = props.getTencentAccessTokenRedisKey();
  150. java.util.function.Supplier<String> tokenSupplier;
  151. if (tokenRedisKey != null && !tokenRedisKey.isBlank()) {
  152. tokenSupplier = () -> redisTemplate.opsForValue().get(tokenRedisKey);
  153. } else {
  154. // 兜底:使用配置文件中的静态 token
  155. String staticToken = props.getTencentAccessToken();
  156. tokenSupplier = () -> staticToken;
  157. }
  158. return new TencentClient(
  159. tokenSupplier,
  160. props.getTencentActMap(),
  161. objectMapper);
  162. }
  163. @Bean
  164. public TagEventResolver tagEventResolver(@Nullable TiDBColdStore coldStore,
  165. StringRedisTemplate redisTemplate) {
  166. if (coldStore == null) return null;
  167. return new TagEventResolver(redisTemplate, coldStore, props.getTagEventSyncRedisPrefix());
  168. }
  169. @Bean
  170. public ConversionSyncService conversionSyncService(ConversionClient baiduClient,
  171. RedisHotStore hotStore,
  172. TencentClient tencentClient,
  173. @Nullable TiDBColdStore coldStore,
  174. @Nullable TagEventResolver tagEventResolver) {
  175. if (coldStore == null) return null;
  176. return new ConversionSyncService(baiduClient, hotStore, tencentClient, coldStore, tagEventResolver);
  177. }
  178. @Bean
  179. public ConversionSyncRunner conversionSyncRunner(@Nullable ConversionSyncService syncer) {
  180. if (syncer == null) return null;
  181. return new ConversionSyncRunner(syncer,
  182. props.getConversionSyncDateOffsetDays(),
  183. props.getConversionSyncPageSize(),
  184. props.getConversionSyncActs());
  185. }
  186. @Bean
  187. public RetryService retryService(@Nullable TiDBColdStore coldStore, TencentClient tencentClient) {
  188. if (coldStore == null) return null;
  189. return new RetryService(coldStore, tencentClient, props.getCallbackRetryLimit());
  190. }
  191. @Bean
  192. public TagEventSyncService tagEventSyncService(@Nullable TiDBColdStore coldStore,
  193. StringRedisTemplate redisTemplate) {
  194. if (coldStore == null) return null;
  195. // TTL 取同步间隔的 3 倍,避免表中已删除的 tag 在 Redis 长期残留
  196. Duration ttl = props.getTagEventSyncInterval().multipliedBy(3);
  197. return new TagEventSyncService(coldStore, redisTemplate,
  198. props.getTagEventSyncRedisPrefix(), ttl);
  199. }
  200. // ─── ColdWorker ─────────────────────────────────────────────────────────
  201. @Bean
  202. public ColdWorker coldWorker(RedisHotStore hotStore, @Nullable TiDBColdStore coldStore,
  203. ObjectMapper objectMapper) {
  204. if (coldStore == null) return null;
  205. return new ColdWorker(hotStore, coldStore,
  206. props.getWorkerGroup(), props.getWorkerConsumer(),
  207. props.getWorkerBatch(), null,
  208. props.getRedisStreamMaxLen(), objectMapper);
  209. }
  210. // ─── MediaPlacement(腾讯)───────────────────────────────────────────────
  211. @Bean
  212. public MediaPlacement tencentPlacement() {
  213. MediaPlacement p = new MediaPlacement();
  214. p.setBaiduMediaId(props.getBaiduMediaId());
  215. p.setBaiduAppId(props.getBaiduAppId());
  216. p.setBaiduTagId(props.getBaiduTagId());
  217. p.setBidFloor(props.getBaiduBidFloor());
  218. p.setActionTypes(List.of(0, 1, 2));
  219. Map<String, MediaPlacement.BaiduAppPlacement> platforms = new HashMap<>();
  220. if (props.getBaiduAndroidAppId() != null && !props.getBaiduAndroidAppId().isBlank()) {
  221. MediaPlacement.BaiduAppPlacement android = new MediaPlacement.BaiduAppPlacement();
  222. android.setAppId(props.getBaiduAndroidAppId());
  223. android.setTagIds(props.getBaiduAndroidTagIds());
  224. platforms.put("android", android);
  225. }
  226. if (props.getBaiduIosAppId() != null && !props.getBaiduIosAppId().isBlank()) {
  227. MediaPlacement.BaiduAppPlacement ios = new MediaPlacement.BaiduAppPlacement();
  228. ios.setAppId(props.getBaiduIosAppId());
  229. ios.setTagIds(props.getBaiduIosTagIds());
  230. platforms.put("ios", ios);
  231. }
  232. if (!platforms.isEmpty()) p.setPlatforms(platforms);
  233. return p;
  234. }
  235. // ─── 后台任务调度 ────────────────────────────────────────────────────────
  236. @Component
  237. static class BackgroundTasks implements ApplicationRunner {
  238. private static final Logger taskLog = LoggerFactory.getLogger(BackgroundTasks.class);
  239. @Autowired private AppProperties props;
  240. @Autowired(required = false) private ColdWorker coldWorker;
  241. @Autowired(required = false) private ConversionSyncRunner conversionSyncRunner;
  242. @Autowired(required = false) private RetryService retryService;
  243. @Autowired(required = false) private TagEventSyncService tagEventSyncService;
  244. @Autowired(required = false) private LeaderElection leaderElection;
  245. private final AtomicBoolean stopped = new AtomicBoolean(false);
  246. private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
  247. Thread t = new Thread(r);
  248. t.setDaemon(true);
  249. return t;
  250. });
  251. @Override
  252. public void run(ApplicationArguments args) {
  253. // 冷路径 Worker
  254. if (coldWorker != null) {
  255. executor.submit(() -> {
  256. while (!stopped.get()) {
  257. try {
  258. coldWorker.runOnce();
  259. } catch (Exception e) {
  260. taskLog.error("cold worker: {}", e.getMessage(), e);
  261. sleep(1000);
  262. }
  263. }
  264. });
  265. taskLog.info("Cold worker started");
  266. }
  267. // 转化同步
  268. if (conversionSyncRunner != null && props.isConversionSyncEnabled()) {
  269. if (props.isSkipLeaderElection()) {
  270. executor.submit(() -> runConversionSync(() -> stopped.get()));
  271. taskLog.info("Conversion sync started (skip leader election)");
  272. } else if (leaderElection != null) {
  273. executor.submit(() ->
  274. leaderElection.run(
  275. "adx:lock:tencent:conversion-sync",
  276. props.getTaskLockTtl(), props.getTaskLockRenewInterval(), props.getTaskLockRetryInterval(),
  277. stopped::get,
  278. (jobStop) -> runConversionSync(jobStop),
  279. e -> taskLog.error("tencent conversion sync leader: {}", e.getMessage(), e)
  280. )
  281. );
  282. taskLog.info("Conversion sync leader election started");
  283. }
  284. } else {
  285. taskLog.warn("Conversion sync NOT started: runner={}, enabled={}",
  286. conversionSyncRunner != null, props.isConversionSyncEnabled());
  287. }
  288. // 回调重试
  289. if (retryService != null && props.isCallbackRetryEnabled()) {
  290. if (props.isSkipLeaderElection()) {
  291. executor.submit(() -> runCallbackRetry(() -> stopped.get()));
  292. taskLog.info("Callback retry started (skip leader election)");
  293. } else if (leaderElection != null) {
  294. executor.submit(() ->
  295. leaderElection.run(
  296. "adx:lock:tencent:callback-retry",
  297. props.getTaskLockTtl(), props.getTaskLockRenewInterval(), props.getTaskLockRetryInterval(),
  298. stopped::get,
  299. (jobStop) -> runCallbackRetry(jobStop),
  300. e -> taskLog.error("tencent callback retry leader: {}", e.getMessage(), e)
  301. )
  302. );
  303. taskLog.info("Callback retry leader election started");
  304. }
  305. } else {
  306. taskLog.warn("Callback retry NOT started: retryService={}, enabled={}",
  307. retryService != null, props.isCallbackRetryEnabled());
  308. }
  309. // 广告位回传方式同步
  310. if (tagEventSyncService != null && props.isTagEventSyncEnabled()) {
  311. if (props.isSkipLeaderElection()) {
  312. executor.submit(() -> runTagEventSync(() -> stopped.get()));
  313. taskLog.info("Tag event sync started (skip leader election)");
  314. } else if (leaderElection != null) {
  315. executor.submit(() ->
  316. leaderElection.run(
  317. "adx:lock:tencent:tag-event-sync",
  318. props.getTaskLockTtl(), props.getTaskLockRenewInterval(), props.getTaskLockRetryInterval(),
  319. stopped::get,
  320. (jobStop) -> runTagEventSync(jobStop),
  321. e -> taskLog.error("tencent tag event sync leader: {}", e.getMessage(), e)
  322. )
  323. );
  324. taskLog.info("Tag event sync leader election started");
  325. }
  326. } else {
  327. taskLog.warn("Tag event sync NOT started: service={}, enabled={}",
  328. tagEventSyncService != null, props.isTagEventSyncEnabled());
  329. }
  330. }
  331. private void runConversionSync(LeaderElection.StopSignal jobStop) {
  332. long intervalMs = props.getConversionSyncInterval().toMillis();
  333. taskLog.info("[ConversionSync] task started, interval={}ms", intervalMs);
  334. while (!jobStop.isStopped()) {
  335. try {
  336. taskLog.info("[ConversionSync] executing...");
  337. ConversionSyncService.SyncResult r = conversionSyncRunner.runOnce();
  338. taskLog.info("[ConversionSync] done: fetched={} sent={} failed={}", r.fetched.get(), r.sent.get(), r.failed.get());
  339. } catch (Exception e) {
  340. taskLog.error("[ConversionSync] error: {}", e.getMessage(), e);
  341. }
  342. taskLog.info("[ConversionSync] sleeping {}ms until next run", intervalMs);
  343. sleepResponsive(intervalMs, jobStop);
  344. }
  345. taskLog.info("[ConversionSync] task stopped");
  346. }
  347. @Scheduled(cron = "0 17 1,7,10,16,20,23 * * ?")
  348. public void runDelayedConversionSync() {
  349. if (conversionSyncRunner == null || !props.isConversionSyncEnabled()) {
  350. return;
  351. }
  352. if (stopped.get()) {
  353. return;
  354. }
  355. Runnable job = () -> {
  356. try {
  357. taskLog.info("[ConversionBackfill] executing for offsets=1..7");
  358. ConversionSyncService.SyncResult r = conversionSyncRunner.runForOffsets(List.of(-1, -2, -3, -4, -5, -6, -7));
  359. taskLog.info("[ConversionBackfill] done: fetched={} matched={} sent={} failed={} skipped={} alreadySent={}",
  360. r.fetched.get(), r.matched.get(), r.sent.get(), r.failed.get(),
  361. r.skipped.get(), r.alreadySent.get());
  362. } catch (Exception e) {
  363. taskLog.error("[ConversionBackfill] error: {}", e.getMessage(), e);
  364. }
  365. };
  366. if (props.isSkipLeaderElection() || leaderElection == null) {
  367. job.run();
  368. return;
  369. }
  370. executor.submit(() ->
  371. leaderElection.runOnce(
  372. "adx:lock:tencent:conversion-backfill",
  373. props.getTaskLockTtl(), props.getTaskLockRenewInterval(),
  374. stopped::get,
  375. stop -> job.run(),
  376. e -> taskLog.error("tencent conversion backfill leader: {}", e.getMessage(), e)
  377. )
  378. );
  379. }
  380. private void runCallbackRetry(LeaderElection.StopSignal jobStop) {
  381. long intervalMs = props.getCallbackRetryInterval().toMillis();
  382. taskLog.info("[CallbackRetry] task started, interval={}ms, limit={}", intervalMs, props.getCallbackRetryLimit());
  383. while (!jobStop.isStopped()) {
  384. try {
  385. taskLog.info("[CallbackRetry] executing...");
  386. RetryService.RetryResult r = retryService.retryTencentCallbacks(props.getCallbackRetryLimit());
  387. taskLog.info("[CallbackRetry] done: fetched={} sent={} failed={}", r.fetched, r.sent, r.failed);
  388. } catch (Exception e) {
  389. taskLog.error("[CallbackRetry] error: {}", e.getMessage(), e);
  390. }
  391. taskLog.info("[CallbackRetry] sleeping {}ms until next run", intervalMs);
  392. sleepResponsive(intervalMs, jobStop);
  393. }
  394. taskLog.info("[CallbackRetry] task stopped");
  395. }
  396. private void runTagEventSync(LeaderElection.StopSignal jobStop) {
  397. long intervalMs = props.getTagEventSyncInterval().toMillis();
  398. taskLog.info("[TagEventSync] task started, interval={}ms", intervalMs);
  399. while (!jobStop.isStopped()) {
  400. try {
  401. int n = tagEventSyncService.syncOnce();
  402. taskLog.info("[TagEventSync] done: synced={}", n);
  403. } catch (Exception e) {
  404. taskLog.error("[TagEventSync] error: {}", e.getMessage(), e);
  405. }
  406. sleepResponsive(intervalMs, jobStop);
  407. }
  408. taskLog.info("[TagEventSync] task stopped");
  409. }
  410. private static void sleepResponsive(long ms, LeaderElection.StopSignal jobStop) {
  411. long deadline = System.currentTimeMillis() + ms;
  412. while (!jobStop.isStopped()) {
  413. long remaining = deadline - System.currentTimeMillis();
  414. if (remaining <= 0) break;
  415. try {
  416. Thread.sleep(Math.min(remaining, 200));
  417. } catch (InterruptedException e) {
  418. Thread.currentThread().interrupt();
  419. break;
  420. }
  421. }
  422. }
  423. private static void sleep(long ms) {
  424. try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
  425. }
  426. }
  427. }