知識庫 / Spring RSS 訂閱

Reddit應用第五次改進

REST,Spring
HongKong
4
03:59 AM · Dec 06 ,2025

1. 概述

讓我們繼續推進 Reddit 應用程序,作為我們持續進行的案例研究。

2. 在帖子評論時發送電子郵件通知

Reddit 缺少電子郵件通知——非常簡單。我希望看到的是——當有人在我的帖子上發表評論時,我收到一封簡短的電子郵件通知。

因此,簡單地説,這個功能的目的是發送評論電子郵件通知。

我們將實現一個簡單的調度器,它會檢查:

  • 哪些用户應該收到帖子回覆的電子郵件通知
  • 用户是否收到了帖子回覆到他們的 Reddit 收件箱

它會簡單地發送一封包含未讀帖子回覆的電子郵件通知。

2.1. 用户偏好

首先,我們需要修改我們的 Preference 實體和 DTO,添加以下內容:

private boolean sendEmailReplies;

允許用户選擇是否接收包含帖子回覆的電子郵件通知。

2.2. 通知調度器

以下是我們的簡單調度器:

@Component
public class NotificationRedditScheduler {

    @Autowired
    private INotificationRedditService notificationRedditService;

    @Autowired
    private PreferenceRepository preferenceRepository;

    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void checkInboxUnread() {
        List<Preference> preferences = preferenceRepository.findBySendEmailRepliesTrue();
        for (Preference preference : preferences) {
            notificationRedditService.checkAndNotify(preference);
        }
    }
}

請注意,調度器每小時運行一次——當然,如果需要,我們也可以採用更短的週期。

2.3. 通知服務

現在,我們來討論一下我們的通知服務:

@Service
public class NotificationRedditService implements INotificationRedditService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private static String NOTIFICATION_TEMPLATE = "You have %d unread post replies.";
    private static String MESSAGE_TEMPLATE = "%s replied on your post %s : %s";

    @Autowired
    @Qualifier("schedulerRedditTemplate")
    private OAuth2RestTemplate redditRestTemplate;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private UserRepository userRepository;

    @Override
    public void checkAndNotify(Preference preference) {
        try {
            checkAndNotifyInternal(preference);
        } catch (Exception e) {
            logger.error(
              "Error occurred while checking and notifying = " + preference.getEmail(), e);
        }
    }

    private void checkAndNotifyInternal(Preference preference) {
        User user = userRepository.findByPreference(preference);
        if ((user == null) || (user.getAccessToken() == null)) {
            return;
        }

        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(user.getAccessToken());
        token.setRefreshToken(new DefaultOAuth2RefreshToken((user.getRefreshToken())));
        token.setExpiration(user.getTokenExpiration());
        redditRestTemplate.getOAuth2ClientContext().setAccessToken(token);

        JsonNode node = redditRestTemplate.getForObject(
          "https://oauth.reddit.com/message/selfreply?mark=false", JsonNode.class);
        parseRepliesNode(preference.getEmail(), node);
    }

    private void parseRepliesNode(String email, JsonNode node) {
        JsonNode allReplies = node.get("data").get("children");
        int unread = 0;
        for (JsonNode msg : allReplies) {
            if (msg.get("data").get("new").asBoolean()) {
                unread++;
            }
        }
        if (unread == 0) {
            return;
        }

        JsonNode firstMsg = allReplies.get(0).get("data");
        String author = firstMsg.get("author").asText();
        String postTitle = firstMsg.get("link_title").asText();
        String content = firstMsg.get("body").asText();

        StringBuilder builder = new StringBuilder();
        builder.append(String.format(NOTIFICATION_TEMPLATE, unread));
        builder.append("\n");
        builder.append(String.format(MESSAGE_TEMPLATE, author, postTitle, content));
        builder.append("\n");
        builder.append("Check all new replies at ");
        builder.append("https://www.reddit.com/message/unread/");

        eventPublisher.publishEvent(new OnNewPostReplyEvent(email, builder.toString()));
    }
}

請注意:

  • 我們調用 Reddit API 獲取所有回覆,然後逐一檢查它們以確定是否為“未讀”。
  • 如果存在未讀回覆,我們將觸發事件以向該用户發送電子郵件通知。

2.4. 新回覆事件

以下是我們的簡單事件:

public class OnNewPostReplyEvent extends ApplicationEvent {
    private String email;
    private String content;

    public OnNewPostReplyEvent(String email, String content) {
        super(email);
        this.email = email;
        this.content = content;
    }
}

2.5. 回覆監聽器

以下是我們的監聽器:

@Component
public class ReplyListener implements ApplicationListener<OnNewPostReplyEvent> {
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private Environment env;

    @Override
    public void onApplicationEvent(OnNewPostReplyEvent event) {
        SimpleMailMessage email = constructEmailMessage(event);
        mailSender.send(email);
    }

    private SimpleMailMessage constructEmailMessage(OnNewPostReplyEvent event) {
        String recipientAddress = event.getEmail();
        String subject = "New Post Replies";
        SimpleMailMessage email = new SimpleMailMessage();
        email.setTo(recipientAddress);
        email.setSubject(subject);
        email.setText(event.getContent());
        email.setFrom(env.getProperty("support.email"));
        return email;
    }
}

3. 會話併發控制

接下來,我們設置更嚴格的規則,限制應用程序允許的併發會話數量。更重要的是——我們不應允許併發會話

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.sessionManagement()
          .maximumSessions(1)
          .maxSessionsPreventsLogin(true);
}

請注意——由於我們使用了自定義的 UserDetails 實現,因此我們需要覆蓋 equals()hashCode() 方法,因為會話控制策略存儲所有 principals 在一個 map 中,並且需要能夠檢索它們。

public class UserPrincipal implements UserDetails {

    private User user;

    @Override
    public int hashCode() {
        int prime = 31;
        int result = 1;
        result = (prime * result) + ((user == null) ? 0 : user.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        UserPrincipal other = (UserPrincipal) obj;
        if (user == null) {
            if (other.user != null) {
                return false;
            }
        } else if (!user.equals(other.user)) {
            return false;
        }
        return true;
    }
}

4. 分離 API Servlet

應用程序現在既為前端服務,也為 API 服務,均由同一個 Servlet 處理,這並不是理想的做法。

現在,我們應該將這兩個主要職責分開,並將它們分別放入 兩個不同的 Servlet

@Bean
public ServletRegistrationBean frontendServlet() {
    ServletRegistrationBean registration = 
      new ServletRegistrationBean(new DispatcherServlet(), "/*");

    Map<String, String> params = new HashMap<String, String>();
    params.put("contextClass", 
      "org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
    params.put("contextConfigLocation", "org.baeldung.config.frontend");
    registration.setInitParameters(params);
    
    registration.setName("FrontendServlet");
    registration.setLoadOnStartup(1);
    return registration;
}

@Bean
public ServletRegistrationBean apiServlet() {
    ServletRegistrationBean registration = 
      new ServletRegistrationBean(new DispatcherServlet(), "/api/*");
    
    Map<String, String> params = new HashMap<String, String>();
    params.put("contextClass", 
      "org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
    params.put("contextConfigLocation", "org.baeldung.config.api");
    
    registration.setInitParameters(params);
    registration.setName("ApiServlet");
    registration.setLoadOnStartup(2);
    return registration;
}

@Override
protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
    application.sources(Application.class);
    return application;
}

請注意,我們現在有一個前端servlet來處理所有前端請求,並僅啓動一個專門用於前端的Spring上下文;然後我們有一個API Servlet,它啓動了一個完全不同的Spring上下文,用於API。

此外,這一點非常重要:這兩個servlet的Spring上下文是子上下文。由SpringApplicationBuilder創建的父上下文掃描root包中的常見配置,例如持久化、服務等。

以下是我們的WebFrontendConfig

@Configuration
@EnableWebMvc
@ComponentScan({ "org.baeldung.web.controller.general" })
public class WebFrontendConfig implements WebMvcConfigurer {

    @Bean
    public static PropertySourcesPlaceholderConfigurer 
      propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home");
        ...
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}

以及 WebApiConfig:

@Configuration
@EnableWebMvc
@ComponentScan({ "org.baeldung.web.controller.rest", "org.baeldung.web.dto" })
public class WebApiConfig implements WebMvcConfigurer {

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}

5. 展開 RSS 鏈接

最後,我們將改進與 RSS 鏈接的處理方式。

有時,RSS 鏈接會通過外部服務(如 Feedburner)進行縮短或重定向——因此,當我們加載應用程序中的 RSS 鏈接時,我們需要確保通過所有重定向,直到我們到達真正我們關心的主 URL。

例如,當我們將文章鏈接發佈到 Reddit 時,我們實際上發佈的是正確的、原始的 URL。

@RequestMapping(value = "/url/original")
@ResponseBody
public String getOriginalLink(@RequestParam("url") String sourceUrl) {
    try {
        List<String> visited = new ArrayList<String>();
        String currentUrl = sourceUrl;
        while (!visited.contains(currentUrl)) {
            visited.add(currentUrl);
            currentUrl = getOriginalUrl(currentUrl);
        }
        return currentUrl;
    } catch (Exception ex) {
        // log the exception
        return sourceUrl;
    }
}

private String getOriginalUrl(String oldUrl) throws IOException {
    URL url = new URL(oldUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(false);
    String originalUrl = connection.getHeaderField("Location");
    connection.disconnect();
    if (originalUrl == null) {
        return oldUrl;
    }
    if (originalUrl.indexOf("?") != -1) {
        return originalUrl.substring(0, originalUrl.indexOf("?"));
    }
    return originalUrl;
}

請注意以下幾點:

  • 我們處理多級重定向
  • 我們還跟蹤所有已訪問的 URL 以避免重定向循環

6. 結論

這就是幾個關鍵改進,旨在提升 Reddit 應用程序的質量。下一步是進行 API 性能測試,以評估其在生產環境中的表現。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.