spring-cloud客户端负载均衡(初试)

目录结构

spring-cloud客户端负载均衡(初试)_第1张图片

maven

	WeiXinClient
	WeiXinClient
	1.0
	jar

	WeiXinClient
	weixin client of loadbalance

	
		org.springframework.boot
		spring-boot-starter-parent
		1.4.2.RELEASE
		 
	

	
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter
			
        		
            		org.springframework.boot
            		spring-boot-starter-logging
        		
    		
		
		
    		org.springframework.boot
    		spring-boot-starter-log4j2
		
		
			org.springframework.cloud
			spring-cloud-starter-ribbon
		
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.cloud
				spring-cloud-dependencies
				Brixton.BUILD-SNAPSHOT
				pom
				import
			
		
	

	
		weixinclient
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

	
		
			spring-snapshots
			Spring Snapshots
			https://repo.spring.io/snapshot
			
				true
			
		
		
			spring-milestones
			Spring Milestones
			https://repo.spring.io/milestone
			
				false
			
		
	

application.yml

spring:
 application:
   name: WeiXinClient

server:
 port: 8999

logging:
 config: classpath:log4j2.xml
 
WeiXinClient:
 ribbon:
  eureka:
   enabled: false
  listOfServers: 172.24.3.64:8080,172.24.3.64:9092
  ServerListRefreshInterval: 15000

log4j2.xml





    
           
           
               
          

          
          
               
               
               
               
                    
                    
                    
               
          
          
          
          
               
               
               
               
                    
                    
                    
               
          
     
     
           
          	
          	
          	
          
     

APP.java

package com.guosen.weixin.client;

import java.nio.charset.Charset;
import java.util.List;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

/**
 * 发送微信client端
 * 
 * 创建于2016年12月12日
 * @author guosen
 *
 */
@SpringBootApplication
@RibbonClient(name = "WeiXinClient", configuration = WeiXinClientConfiguration.class)
public class App {
	
	@LoadBalanced
	@Bean
	RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		List>  converterList = restTemplate.getMessageConverters();
		
		int count = -1;
		for (int i = 0; i < converterList.size(); i++) {
			HttpMessageConverter message = converterList.get(i);
			if (message.getClass() == StringHttpMessageConverter.class) {
				count = i;
				break;
			}
		}
		StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
		converterList.set(count, stringConverter);
		return restTemplate;
	}
	
	
    public static void main( String[] args ){
    	SpringApplication.run(App.class, args);
    }
}

WeiXinClientConfiguration.java

package com.guosen.weixin.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AvailabilityFilteringRule;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.PingUrl;

public class WeiXinClientConfiguration {
	@Autowired
	IClientConfig ribbonClientConfig;
	
	@Bean
	public IPing ribbonPing(IClientConfig config) {
		return new PingUrl();
	}
	
	@Bean
	public IRule ribbonRule(IClientConfig config) {
		return new AvailabilityFilteringRule();
	}
}

ClientController.java

package com.guosen.weixin.client;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class ClientController {
	private static final Logger logger = LoggerFactory.getLogger(ClientController.class);
	@Autowired
	RestTemplate restTemplate;
	/**
	 * 通过get方法发送微信,get请求信息必须包括(touser、toparty、totag)中的一种、agentid、content
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/send/text/byget", method = RequestMethod.GET)
	public String sendTextByGet(HttpServletRequest request){
		// 消息
		Map map = new HashMap();
		ObjectMapper om = new ObjectMapper();
		Map results = new HashMap();
		String result = "";
		
		String touser = request.getParameter("touser");
		String toparty = request.getParameter("toparty");
		String totag = request.getParameter("totag");
		String agentid = request.getParameter("agentid");
		String content = request.getParameter("content");
		
		if ((null == touser || "".equals(touser)) && (null == toparty || "".equals(toparty)) && (null == totag || "".equals(totag))) {
			results.put("errcode", 9999);
			results.put("errmsg", "touser、toparty、totag必须选填一个");
			try {
				result = om.writeValueAsString(results);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			return result;
		}
		
		boolean formatFlag = false;
		int agent = 0;
		try {
			agent = Integer.parseInt(agentid);
			formatFlag = true;
		} catch (NumberFormatException e2) {
			e2.printStackTrace();
		}
		if (null == agentid || "".equals(agentid) || !formatFlag) {
			results.put("errcode", 9999);
			results.put("errmsg", "agentid不能为空,并且为数字");
			try {
				result = om.writeValueAsString(results);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			return result;
		}
		
		if (null == content || "".equals(content)) {
			results.put("errcode", 9999);
			results.put("errmsg", "content不能为空,并且必填");
			try {
				result = om.writeValueAsString(results);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			return result;
		}
		
		Map cmap = new HashMap();
		cmap.put("content", content);
		map.put("safe", 0);
		map.put("msgtype", "text");
		map.put("agentid", agent);
		map.put("text", cmap);
		if (null != touser && !"".equals(touser)) {
			map.put("touser", touser);
		}
		if (null != toparty && !"".equals(toparty)) {
			map.put("toparty", toparty);
		}
		if (null != totag && !"".equals(totag)) {
			map.put("totag", totag);
		}
		
		// 将参数map转换为json对象并且请求发送服务
		try {
			String data = om.writeValueAsString(map);
			logger.info(data);
			result = this.restTemplate.postForObject("http://WeiXinClient/sendText", data, String.class);
		} catch (Exception e) {
			logger.error("发送微信信息异常", e);
			results.put("errcode", 9999);
			results.put("errmsg", e.getMessage());
			try {
				result = om.writeValueAsString(results);
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * 通过post json字符串的方式发送微信,post内容为{"touser":"xxx|xxx","content":"xxx","agentid":xx} 其中touser可以改为toparty、totag
	 * @param requestData
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/send/text/bypost", method = RequestMethod.POST)
	public String sendTextByPost(@RequestBody String requestData){
		// 消息
		ObjectMapper om = new ObjectMapper();
		Map results = new HashMap();
		String result = "";
		
		// 将参数map转换为json对象并且请求发送服务
		try {
			Map requestMap = om.readValue(requestData, Map.class);
			requestMap.put("safe", 0);
			requestMap.put("msgtype", "text");
			Map cmap = new HashMap();
			cmap.put("content", (String)requestMap.get("content"));
			requestMap.put("text", cmap);
			requestMap.remove("content");
			String data = om.writeValueAsString(requestMap);
			
			result = this.restTemplate.postForObject("http://WeiXinClient/sendText", data, String.class);
		} catch (Exception e) {
			logger.error("发送微信信息异常", e);
			results.put("errcode", 9999);
			results.put("errmsg", e.getMessage());
			try {
				result = om.writeValueAsString(results);
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * 通过post字符串的方式发送微信,post内容为content=xxxx&agentid=xxx&touser=xxx
	 * @param content
	 * @param touser
	 * @param agentid
	 * @return
	 */
	@RequestMapping(value = "/entp", method = RequestMethod.POST)
	public String sendText(String content, String touser, String agentid){
		// 消息
		ObjectMapper om = new ObjectMapper();
		Map results = new HashMap();
		String result = "";
		
		// 将参数map转换为json对象并且请求发送服务
		try {
			Map requestMap = new HashMap();
			requestMap.put("safe", 0);
			requestMap.put("msgtype", "text");
			Map cmap = new HashMap();
			cmap.put("content", content);
			requestMap.put("text", cmap);
			requestMap.put("touser", touser);
			requestMap.put("agentid", agentid);
			String data = om.writeValueAsString(requestMap);
			result = this.restTemplate.postForObject("http://WeiXinClient/sendText", data, String.class);
		} catch (Exception e) {
			logger.error("发送微信信息异常", e);
			results.put("errcode", 9999);
			results.put("errmsg", e.getMessage());
			try {
				result = om.writeValueAsString(results);
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
		return result;
	}
}


你可能感兴趣的:(java)