外部へのhttps通信処理をspring bootで実装しています。
通知先が多いと送信処理に時間がかかってしまう為、マルチスレッドを使って処理時間を減らそうと思います。
処理ロジックは下記の通りです。
・画面から配信データを入力、送信ボタンを押す
・DBから通知先データのリストを取得
・通知先データの数だけ送信処理を繰り返す(ここでマルチスレッドを実装)
・送信処理を行った件数を画面に出力する
@EnableAsync、@Asyncを使用して実行時のログを見てみたのですが、同期的な実行結果になってしまいました。
1つの送信処理にかかっている時間は100ms台~500ms台と幅が出ています。
処理件数が少ないからこのような実行結果になっているのかもしれませんが、非同期処理を実装するにあたって不足しているアノテーションや
コードの改善案などありましたらご教授頂きたいです。
■DemoApplication.class
@SpringBootApplication @EnableAsync public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication .class, args); } }
@Controller public class DemoController { @Autowired DemoService service; //略 @PostMapping(value = "/") public String subscribe(@ModelAttribute SendForm form, RedirectAttributes redirectAttribute) { List<DemoData> list = this.service.getTargetList(); int num = list.size(); this.service.send(list, form); redirectAttribute.addFlashAttribute("num", num); return "redirect:/"; } }
@Service public class DemoService { @Autowired DemoConfiguration config; private static final Log log = LogFactory.getLog(DemoService.class); //略 public void send(List<DemoData> list, SendForm form) { final String PUBLIC_KEY = this.config.getPublicKey(); final String PRIVATE_KEY = this.config.getPrivateKey(); final String SUBJECT = form.getTitle(); int max = list.size(); String payload = ""; ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); DemoService demoService = null; try { demoService = new DemoService(PUBLIC_KEY, PRIVATE_KEY, SUBJECT); payload = mapper.writeValueAsString(form); } catch (GeneralSecurityException | JsonProcessingException e) { e.printStackTrace(); } for (int i = 0; i < max; i++) { String subscriptionJson = list.get(i).getJson(); this.asyncSend(i,subscriptionJson, mapper, payload, demoService); } } @Async private void asyncSend(int i, String subscriptionJson, ObjectMapper mapper, String payload, DemoService demoService) { try { Subscription subscription = mapper.readValue(subscriptionJson, Subscription.class); Notification notification = new Notification(subscription, payload); demoService.send(notification); } catch (Exception e) { System.out.println(e.getMessage()); } } }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/11/21 06:44