提交 c75a98e9 authored 作者: liupengfei's avatar liupengfei

--no commit message

上级 866daadb
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,6 +13,10 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerA
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import com.alibaba.druid.pool.DruidDataSource;
@EnableFeignClients
@EnableEurekaClient
......@@ -17,7 +24,13 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class })
// 系统会去入口类的同级包以及下级包中去扫描实体类,因此我们建议入口类的位置在groupId+arctifactID组合的包名下。
public class ThirdStart {
@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) {
......@@ -25,4 +38,19 @@ public class ThirdStart {
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.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
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();
}
};
}
/*@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 设置缓存过期时间
// rcm.setDefaultExpiration(60);//秒
return rcm;
}*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
//.entryTtl(Duration.ofHours(1)) // 设置缓存有效期一小时
;
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@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.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 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.zrqx"))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("sysUser 测试使用 Swagger2 构建RESTful API")
//描述
.description("sysUser服务 API 描述")
//创建人
.contact(new Contact("陈新昌", "www.baidu.com", "cxinchang@126.com"))
//版本号
.version("3.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);
}
// @Bean
// public Decoder feignDecoder() {
// HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(customObjectMapper());
// ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
// return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
// }
// @Bean
// public Encoder feignEncoder(){
// HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(customObjectMapper());
// ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
// return new SpringEncoder(objectFactory);
// }
//
// public ObjectMapper customObjectMapper(){
// ObjectMapper objectMapper = new ObjectMapper();
// //Customize as much as you want
// objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
// return objectMapper;
// }
}
\ 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 {
private static 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.fail(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.fail(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
......@@ -15,8 +15,8 @@ import com.zrqx.core.client.vo.third.pay.payquery.PayQueryReturnVo;
import com.zrqx.core.client.vo.third.pay.refundquery.BaseRefundQueryReturnVo;
import com.zrqx.core.enums.third.pay.PayTypeEnum;
import com.zrqx.core.util.response.CallBack;
import com.zrqx.core.util.spring.SpringContextUtils;
import com.zrqx.third.pay.interfaces.payType.PayTypeInterface;
import com.zrqx.third.util.SpringContextUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
......
package com.zrqx.third.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.zrqx.core.util.spring.BaseSpringContextUtils;
@Component
public class SpringContextUtils extends BaseSpringContextUtils {
private static final Logger logger = LoggerFactory.getLogger(SpringContextUtils.class);
// @Value("${test-environment}")
// private Boolean testEnvironment;
/**
* 初始化操作
* @author lpf
* @date: 2019年1月3日 上午9:17:01
*/
public void init(){
}
@Override
public Logger getLog() {
return SpringContextUtils.logger;
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论