提交 d8b5113e authored 作者: lvwei's avatar lvwei

--no commit message

上级 79780020
package com.zrqx.third;
package com.zrqx;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
......@@ -10,22 +13,45 @@ import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import tk.mybatis.spring.annotation.MapperScan;
import com.alibaba.druid.pool.DruidDataSource;
@EnableFeignClients
@EnableEurekaClient
@EnableHystrix
@EnableHystrixDashboard
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class })
@SpringBootApplication
// 系统会去入口类的同级包以及下级包中去扫描实体类,因此我们建议入口类的位置在groupId+arctifactID组合的包名下。
public class Application {
public class ThirdStart {
private final static Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
private final static Logger logger = LoggerFactory.getLogger(ThirdStart.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
SpringApplication.run(ThirdStart.class, args);
logger.info("thrid服务已启动.....");
}
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);// 用户名
dataSource.setPassword(password);// 密码
dataSource.setInitialSize(10);
dataSource.setMaxActive(200);
dataSource.setMaxWait(60000);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(false);
dataSource.setTestWhileIdle(true);
dataSource.setPoolPreparedStatements(false);
return dataSource;
}
}
package com.zrqx.third.commons.config;
import java.lang.reflect.Method;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* redis 配置类
* @author pc
*
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
// key序列化方式,但是如果方法上有Long等非String类型的话,会报类型转换错误
// 所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer
RedisSerializer<String> redisSerializer = new StringRedisSerializer();// Long类型不可以会出现异常信息;
redisTemplate.setKeySerializer(redisSerializer);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
\ No newline at end of file
package com.zrqx.third.commons.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 访问地址
* http://ip:port/swagger-ui.html
最常用的5个注解
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
其它若干
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiClass
@ApiError
@ApiErrors
@ApiParamImplicit
@ApiParamsImplicit
*/
@EnableSwagger2
@Configuration
public class Swagger2Config {
/** 服务环境 {@link EnvironmentEnum} 0 测试|其他正式 */
@Value("${server.environment}")
private String env;
@Bean
public Docket createRestApi() {
if ("0".equals(env)) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.zrqx"))
.paths(PathSelectors.any())
.build();
}
return null;
}
//构建 api文档的详细信息函数
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("third 测试使用 Swagger2 构建RESTful API")
//描述
.description("third服务 API 描述")
//创建人
.contact(new Contact("陈新昌", "www.baidu.com", "cxinchang@126.com"))
//版本号
.version("4.0")
.build();
}
}
\ No newline at end of file
package com.zrqx.third.commons.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
/**
* 跨域支持
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowCredentials(false).maxAge(3600);
}
}
\ No newline at end of file
package com.zrqx.third.commons.interceptor;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.util.response.CallBack;
/**
*controller 异常处理
* @ClassName: CustomExceptionHandler
* @Description: TODO(这里用一句话描述这个类的作用)
* @author 杨振广
* @date 2016-7-14 上午9:45:40
*
*/
@ControllerAdvice
public class CustomExceptionHandler {
Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object handlerException(HttpServletRequest request,HttpServletResponse response,Exception e){
e.printStackTrace();
StackTraceElement[] s = e.getStackTrace();
StringBuffer stes = new StringBuffer(s.length*2);
for (StackTraceElement stackTraceElement : s) {
stes.append(stackTraceElement.toString());
stes.append("\n");
}
String info = "异常时间:"+new Date().toLocaleString()+"\n请求地址:"+request.getRequestURI()+"\n参数:"+request.getQueryString()+"\n"+e.getMessage();
logger.error(info+"\n"+stes.toString());
request.setAttribute("error",info);
request.setAttribute("errorInfo",e.getStackTrace());
return CallBack.exception(e.getMessage());
}
/**
* 参数验证异常处理
* @Title: handlerException
* @Description:
* @param request
* @param response
* @param e BindException
* @return
* @author lpf
* @date: 2018年5月9日 下午5:01:58
*/
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object handlerException(HttpServletRequest request,HttpServletResponse response,BindException e) {
List<ObjectError> errors = e.getAllErrors();
StringBuffer msg = new StringBuffer();
for (ObjectError objectError : errors) {
msg.append(objectError.getDefaultMessage());
msg.append(",");
}
msg.deleteCharAt(msg.length()-1);
return CallBack.validate(msg.toString());
}
/**
* 执行异常处理
* @Description:
* @param e BaseException
* @return
* @date: 2018年5月9日 下午5:01:58
*
*/
@ExceptionHandler(BaseException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object myException(BaseException e) {
return CallBack.fail(e.getMessage());
}
}
\ No newline at end of file
......@@ -47,19 +47,19 @@ public class EmailController {
// 服务器ip
@Value("${email.email_host}")
String EMAIL_HOST;
private String EMAIL_HOST;
// 端口
@Value("${email.email_port}")
String EMAIL_PORT;
private String EMAIL_PORT;
// 账号
@Value("${email.email_account}")
String EMAIL_ACCOUNT;
private String EMAIL_ACCOUNT;
// 密码
@Value("${email.email_password}")
String EMAIL_PASSWORD;
private String EMAIL_PASSWORD;
@Autowired
Redis redis;
private Redis redis;
/**
* 群发 key:收件人地址 value:内容
......
package com.zrqx.third.email;
import com.zrqx.third.email.config.MailInfo;
import com.zrqx.third.email.config.SimpleMail;
public class EmailTest {
public static void main(String[] args) {
System.out.println("1212");
MailInfo mailInfo = new MailInfo();
mailInfo.setMailServerHost("smtp.exmail.qq.com");
mailInfo.setMailServerPort("25"); //25 465 587
mailInfo.setValidate(true);
mailInfo.setUsername("shi_tengfei@worldaffairs.cn");
mailInfo.setPassword("stf19900801");// 您的邮箱密码
mailInfo.setFromAddress("shi_tengfei@worldaffairs.cn");
mailInfo.setToAddress("122995870@qq.com");
mailInfo.setSubject("abcd");
mailInfo.setValidate(true);
//附件
/*String[] attachFileNames={"d:/Sunset.jpg"};
mailInfo.setAttachFileNames(attachFileNames); */
// 这个类主要来发送邮件
//mailInfo.setContent("设置邮箱内容");
//SimpleMail.sendTextMail(mailInfo);// 发送文体格式
StringBuffer demo = new StringBuffer();
demo.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">")
.append("<html>")
.append("<head>")
.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">")
.append("<title>测试邮件</title>")
.append("<style type=\"text/css\">")
.append(".test{font-family:\"Microsoft Yahei\";font-size: 18px;color: red;}")
.append("</style>")
.append("</head>")
.append("<body>")
.append("<img src='http://img0.imgtn.bdimg.com/it/u=2535477532,1479756398&fm=21&gp=0.jpg' />")
.append("<span class=\"test\">大家好,这里是测试Demo</span>")
.append("</body>")
.append("</html>");
mailInfo.setContent(demo.toString());
// SimpleMail.sendHtmlMail(mailInfo);// 发送html格式
SimpleMail.sendTextMail(mailInfo);// 发送html格式
System.out.println("邮件发送成功!!");
}
}
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论