spring整合redis发布订阅操作

1,导入依赖包(省略)

2,spring整合redis发布订阅配置文件



	
	
	
	
		
		
		
		
		
	
	
		
	      
		
		
		
	
	
		
	
 	  
      

	
	

	
	
		
		
		
		
	
	
3,发布订阅:我用的框架是springmvc,在调用时直接注入redisTemplate对象即可发布消息

@Resource(name = "redisTemplate")
private RedisTemplate redisTemplate;

操作实例

发布:

/**
	 * 新增讨论点赞(H5)
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "/addDiscussNice")
	public JsonResult addDiscussNice(HttpServletRequest request, HttpServletResponse response) {
		Long startTime = TimeUtil.getCurrentTimeMillis();// 毫秒值
		HttpSession session = request.getSession();
		String source = request.getParameter("source");
		source = Utils.isEmpty(source) ? "" : source;
		boolean isNeedCrypt = ServletUtils.isNeedCrypt(source);
		String cuserId = (String) session.getAttribute("userId");
		String cryptPd = ServletUtils.getCryptPassword(cuserId);
		boolean isH5 = StringUtils.equals(Constants.SOURCE_HTML5, source);
		// 登录校验
		if (StringUtils.isBlank(cuserId) && !isH5) {
			String token = request.getParameter("token");
			TokenCode tokenCode = TokenCodeUtil.getTokenCode(token);
			if (tokenCode != null && tokenCode.getUserId() != null) {
				cuserId = tokenCode.getUserId();
			} else {
				UserLoggerUtil.getUserLogger(startTime, cuserId, "exchangeExt", "addShopDiscuss", "", "", "",
						ErrorConstants.ERROR_CODE_NAME);
				new JsonResult(ErrorConstants.NO_LOGIN, "用户未登录");
			}
		}
		String data = "";
		try {
			if (isH5) {
				data = request.getParameter("discussNice");
			} else {
				data = request.getParameter("discussNice");
				data = URLDecoder.decode(data, "UTF-8");
				if (isNeedCrypt) {
					data = CryptUtils.decode(data, cryptPd);
				}
			}
			ShopDiscussNiceVo shopDiscussNiceVo = JSONObject.parseObject(data, ShopDiscussNiceVo.class);
			if(shopDiscussNiceVo!=null){
				// 发布
				redisTemplate.convertAndSend("addShopShopDiscussNiceVo", shopDiscussNiceVo);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return new JsonResult("0", "操作成功");
	}

订阅

	/**
	 * 新增讨论点赞
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void addShopShopDiscussNiceVo(Serializable message) {
		if (message != null && message instanceof ShopDiscussNiceVo) {
			ShopDiscussNiceVo shopDiscussNiceVo = (ShopDiscussNiceVo) message;
			//数据处理
			ServiceResult listResult = webShopDiscussNiceService.addShopDiscussNice(shopDiscussNiceVo);
			if (listResult != null && listResult.getCode() == ErrorConstants.RES_SUCCESS) {
				// 记录成功日志
				logger.info("create new movie shop discuss nice is success in" + TimeUtil.GetCurDateTime());
			} else {
				logger.error("create new movie shop discuss nice is fail in" + TimeUtil.GetCurDateTime());
			}
		} else {
			logger.error("the type is error when create new movie shop nice comment in" + TimeUtil.GetCurDateTime());
		}

	}



你可能感兴趣的:(spring整合redis发布订阅操作)