感觉 event bus简单实用,使用 event bus 做一个demo 如下:
@SpringBootApplication
public class SmsEventBusApplication {
public static void main(String[] args) {
SpringApplication.run(SmsEventBusApplication.class, args);
}
}
配置文件
// spring boot 配置方式加载
// 生成多个异步消息
@Configuration
public class EventBusConfig {
@Bean
public AsyncEventBus asyncEventBus(){
return new AsyncEventBus(Executors.newFixedThreadPool(5));
}
}
短信配置文件
@Data
@Component
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix="sms")
@PropertySource(value="classpath:application.properties")
public class SmsConf {
/** 连接路径 */
private String url;
/** 连接账号 */
private String account;
/** 连接密码 */
private String password;
}
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restful风格")
.termsOfServiceUrl("http://www.baidu.com")
.version("1.0")
.build();
}
}
发送短信两种方式 GET POST 定义两种模型
public enum RequestMethodEnum {
GET,
POST;
}
public enum ResponseHandlerEnum {
XML_BEAN{
public ResponseHandler handleResponse (Class clazz){
return new ResponseHandler() {
@Override
public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
return handleResponseXml(response,clazz);
}
};
}
},
JSON_BEAN{
public ResponseHandler handleResponse (Class clazz){
return new ResponseHandler() {
@Override
public T handleResponse(HttpResponse response)throws ClientProtocolException, IOException {
return handleResponseXml(response,clazz);
}
};
}
};
public abstract ResponseHandler handleResponse (Class clazz);
public T handleResponseJson(HttpResponse response,Class clazz)throws ClientProtocolException, IOException {
Gson gson =new GsonBuilder().create();
return gson.fromJson(EntityUtils.toString(response.getEntity(),Consts.UTF_8),clazz);
}
public T handleResponseXml(HttpResponse response,Class clazz)throws ClientProtocolException, IOException {
return XmlParserUtil.parseXml(EntityUtils.toString(response.getEntity(),Consts.UTF_8),clazz);
}
}
@Getter
public enum SmsStatusEnum {
fail(false,"发送失败"),
success(true,"已发送");
private boolean flag;
private Stringmsg;
SmsStatusEnum(boolean flag,String msg) {
this.flag=flag;
this.msg=msg;
}
public static String getValue(boolean flag){
for (SmsStatusEnum e :values()) {
if (flag == e.isFlag()){
return e.getMsg();
}
}
return null;
}
}
// 发起发送短信Controller 主要测试eventBus 只简单传递参数
@Api(tags ="短信发送", description ="mazg")
@RestController
public class SmsController {
private static Stringmobile ="18310886036";
private static Stringcontent ="您的验证码是:{1} 请不要把验证码泄露给其他人。【优品分期】";
@Autowired
private SmsProducersmsProducer;
@ApiOperation(value ="短信发送", httpMethod ="GET")
@RequestMapping(value ="send",method = RequestMethod.GET)
public ResponseEntity send(@RequestParam String mobile){
boolean result =smsProducer.smsSend(combineText(content,mobile),mobile);
return new ResponseEntity(SmsStatusEnum.getValue(result),HttpStatus.OK);
}
private String combineText(String content,final String mobile){
return Splitter.onPattern("\\{[0-9]{1,}\\}").omitEmptyStrings().splitToList(content)
.stream()
.collect(Collectors.joining(mobile));
}
}
消息发送者
// 获取 asyncEventBus 发送
@Component
public class SmsProducer {
@Autowired
private AsyncEventBus asyncEventBus;
@Autowired
private SmsConf smsConf;
public boolean smsSend(final String content,String...mobiles){
try {
Arrays.stream(mobiles).forEach(mobile -> {
SmsEvent smsEvent = SmsEvent.builder().action("send").content(content).mobile(mobile).build();
copy(smsEvent);
asyncEventBus.post(smsEvent);
});
return tue;
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* bean coiper
* @param smsEvent
*/
private void copy(SmsEvent smsEvent){
BeanCopier copier = BeanCopier.create(SmsConf.class,SmsEvent.class,false);
copier.copy(smsConf,smsEvent,null);
}
工具类
// map 转 json ~ json 转 map
public class Class2MapUtil {
private static Gsongson =new GsonBuilder() .enableComplexMapKeySerialization().create();
public static Map convertMap(T t) {
String json=gson.toJson(t,new TypeToken() {
}.getType());
return gson.fromJson(json,new TypeToken>() {
}.getType());
}
public static T convertBean(Map map,Class clazz) {
String json=gson.toJson(map,new TypeToken>() {
}.getType());
return gson.fromJson(json,clazz);
}
}
获取当前类信息方法名称和类名
// 获取当前类名和方法名
public class ClassInfoUtil {
public static String getClassName(){
return Thread.currentThread().getStackTrace()[1].getClassName();
}
public static String getMethodName(){
return Thread.currentThread().getStackTrace()[1].getMethodName();
}
}
Http client 请求封装
public class HttpUtil {
/* 连接超时 */
private int connectTimeOut =6000;
/* socket超时 */
private int socketTimeout =6000;
/* 请求方式 */
private RequestMethodEnum methodEnum;
private URIBuilder builder = new URIBuilder();
private Request request;
public HttpUtil(RequestMethodEnum methodEnum) {
this.methodEnum=methodEnum;
}
public HttpUtil(int connectTimeOut,int socketTimeout,RequestMethodEnum methodEnum) {
this.connectTimeOut=connectTimeOut;
this.socketTimeout=socketTimeout;
this.methodEnum = methodEnum;
}
/**
* 封裝请求参数
* @param map 转换后参数
* @return
*/
public HttpUtil getUrlParameter(String url,Map map) {
this.builder.setPath(url);
map.entrySet().forEach(entry -> {
builder.addParameter(entry.getKey(),entry.getValue().toString());
});
request =this.methodEnum.name().equals("GET")? getRequest(): postRequest();
return this;
}
/**
* 思考可以使用 @Bean 声明
* 封装 get Request 请求
* @return
*/
private Request getRequest() {
try {
request = Request.Get(this.builder.build())
.connectTimeout(connectTimeOut)
.socketTimeout(socketTimeout);
}catch (URISyntaxException e) {
e.printStackTrace();
}
return request;
}
/**
* 思考可以使用 @Bean 声明
* 封装 post Request 请求
* @return
*/
public Request postRequest() {
try {
request = Request.Post(this.builder.build())
.connectTimeout(connectTimeOut)
.socketTimeout(socketTimeout);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return request;
}
/**
* 转换成对应对象
* @param clazz
* @param
* @return
*/
public T toBean(Class clazz,ResponseHandlerEnum responseHandlerEnum){
T t =null;
try {
t =this.request
.execute()
.handleResponse(responseHandlerEnum.handleResponse(clazz));
System.out.println("request success return response info:"+ t.toString());
//SmsThreadLocalHolder.set(t);
}catch (IOException e) {
e.printStackTrace();
}
return t;
}
}
xml 解析 转换
// xml 解析 转换
public class XmlParserUtil {
/**
* @param xml xml 字符串
* @param tClass 实体类
* */
public static T parseXml(String xml,Class tClass){
T t =null;
try {
System.out.println("xml="+xml);
XStream xStream =new XStream();
xStream.processAnnotations(tClass);//通过注解方式的,一定要有这句话
t = (T) xStream.fromXML(xml);
System.out.println("xml parser success className::"+tClass.getSimpleName());
}catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
*
* @param t 实体类
* @return xml 字符串
*/
public static String toXml2String(T t){
String result ="";
try {
XStream xStream =new XStream();
result = (String)xStream.toXML(t);
System.out.println("xml convert success xml::"+result);
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
*
* @param t 实体类
* @return json 字符串
*/
public static String toXml2Json(T t){
String json ="";
try {
XStream xStream =new XStream(new JettisonMappedXmlDriver());
xStream.autodetectAnnotations(true);
json = (String)xStream.toXML(t);
System.out.println("xml convert json success json::"+json);
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
}
ThreadLocal 使用封装
public class SmsThreadLocalHolder{
private static ThreadLocal threadLocal =new ThreadLocal<>();
public static void set(T t){ ;
threadLocal.set((Returnsms)t);
}
public static Returnsms get(){
return threadLocal.get();
}
public static void remove(){
threadLocal.remove();
}
}
短信配置文件
sms.url=http://sh2.ipyy.com/sms.aspx
sms.account=****
sms.password=*****
pom 引用
4.0.0
com.use
sms_eventbus
0.0.1-SNAPSHOT
jar
sms_eventbus
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.2.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
io.springfox
springfox-swagger2
2.6.1
io.springfox
springfox-swagger-ui
2.6.1
org.smartboot.socket
aio-core
1.3.3
com.lmax
disruptor
3.4.2
org.apache.httpcomponents
fluent-hc
4.5.5
com.google.guava
guava
25.0-jre
com.google.code.gson
gson
2.8.5
com.thoughtworks.xstream
xstream
1.4.10
org.springframework.boot
spring-boot-devtools
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin