我正在開發基於REST的web服務,使用彈簧來提供RSS提要。對RSS的更新非常少見(每週幾次),因此我想緩存RSS源,而不是每次有人請求時都建立它。這是我的代碼。我在啓動Web服務器後的第一個請求在SubscriptionEventHandler類中觸發getRssFeed()方法,然後進入SubscriptionRssFeedView並調用buildFeedMetadata,buildFeedItems方法等等,這是正確的。但是,當我做第二個請求,它會跳過getRssFeed()方法SubscriptionEventHandler但buildFeedMetadata,在SubscriptionRssFeedView buildFeedItems方法被調用這反過來又調用getIncidents()和從頭構建RSS。有沒有一種方法可以讓我避免這種情況並緩存RSS,直到我稱之爲@CacheEvictSpring REST緩存RSS AbstractRssFeedView
這裏是我的SubscriptionRssFeedView
@Component("subscriptionRssView")
public class SubscriptionRssFeedView extends AbstractRssFeedView
{
private String base_Url=」http://mycompany.com/」;
private final String feed_title = "My RSS Title ";
private final String feed_desc = "RSS feed desc";
private final String feed_type = "rss_2.0";
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request)
{
feed.setTitle(feed_title);
feed.setDescription(feed_desc);
feed.setLink(base_Url);
feed.setFeedType(feed_type);
super.buildFeedMetadata(model, feed, request);
}
@Override
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
List<Message> messageList = new ArrayList(Arrays.asList(getIncidents()));
List<Item> itemList = new ArrayList<Item>(messageList.size());
for (Message message : messageList)
{
itemList.add(createItem(message));
}
return itemList;
}
private Message[] getIncidents()
{
RestTemplate restTemplate = new RestTemplate();
Message[] message = restTemplate.getForObject("http://xxxxx.com/api/message", Message[].class);
return message;
}
private Item createItem(Message message)
{
Item item = new Item();
item.setLink(getFeedItemURL(message));
item.setTitle(prepareFeedItemTitle(message));
item.setDescription(createDescription(message));
item.setPubDate(getLocalizedDateTimeasDate(message.getT()));
return item;
}
}
我SubscriptionEventHandler
@Component("SubscriptionService")
public class SubscriptionEventHandler implements SubscriptionService
{
@Autowired
private SubscriptionRssFeedView subscriptionRssFeedView;
@Override
@Cacheable("rssFeedCache")
public SubscriptionRssFeedView getRssFeed()
{
return subscriptionRssFeedView;
}
}
我SubscriptionService
@Service
public interface SubscriptionService
{
SubscriptionRssFeedView getRssFeed();
}
我SubscriptionController
@Controller
@RequestMapping("/subscription")
public class SubscriptionController
{
@Autowired
private SubscriptionService subscriptionService;
@RequestMapping(value = "/rss", method = RequestMethod.GET)
public SubscriptionRssFeedView getRSS() throws Exception
{
return subscriptionService.getRssFeed();
}
}
檢查我更新的評論 – artemisian