首页>代码>spring mvc+thymeleaf+Knockout.js整合开发最简单的聊天室实例>/spring-mvc-chat/src/main/java/org/springframework/samples/async/chat/ChatController.java
package org.springframework.samples.async.chat;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

@Controller
@RequestMapping("/mvc/chat")
public class ChatController {

	private final ChatRepository chatRepository;

	private final Map<DeferredResult<List<String>>, Integer> chatRequests =
			new ConcurrentHashMap<DeferredResult<List<String>>, Integer>();


	@Autowired
	public ChatController(ChatRepository chatRepository) {
		this.chatRepository = chatRepository;
	}

	@RequestMapping(method=RequestMethod.GET)
	@ResponseBody
	public DeferredResult<List<String>> getMessages(@RequestParam int messageIndex) {

		final DeferredResult<List<String>> deferredResult = new DeferredResult<List<String>>(null, Collections.emptyList());
		this.chatRequests.put(deferredResult, messageIndex);

		deferredResult.onCompletion(new Runnable() {
			@Override
			public void run() {
				chatRequests.remove(deferredResult);
			}
		});

		List<String> messages = this.chatRepository.getMessages(messageIndex);
		if (!messages.isEmpty()) {
			deferredResult.setResult(messages);
		}

		return deferredResult;
	}

	@RequestMapping(method=RequestMethod.POST)
	@ResponseBody
	public void postMessage(@RequestParam String message) {

		this.chatRepository.addMessage(message);

		// Update all chat requests as part of the POST request
		// See Redis branch for a more sophisticated, non-blocking approach

		for (Entry<DeferredResult<List<String>>, Integer> entry : this.chatRequests.entrySet()) {
			List<String> messages = this.chatRepository.getMessages(entry.getValue());
			entry.getKey().setResult(messages);
		}
	}

}
最近下载更多
wangyoung  LV10 2021年3月5日
安泽源  LV7 2019年5月29日
Onlyli  LV14 2019年5月16日
daidin  LV11 2019年3月8日
小推推  LV19 2019年2月4日
lvtong  LV1 2019年1月16日
我叫大黄啊  LV1 2018年10月26日
1196319567  LV9 2018年9月1日
345311623  LV8 2018年7月26日
yangctz  LV24 2018年7月8日
最近浏览更多
夜起星河  LV8 2023年12月27日
buhuia  LV4 2023年6月7日
ChenZheMeng  LV3 2022年12月21日
win1991  LV6 2022年8月18日
123456qiqiqi  LV1 2022年5月27日
fengshengtian  LV8 2022年4月19日
yuxinnan  LV4 2022年4月11日
唐家俊  LV2 2021年12月25日
494785  LV5 2021年12月15日
liuxiao2  LV16 2021年11月17日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友