提交 86878519 authored 作者: lizhuo's avatar lizhuo

--no commit message

上级 60d2040e
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="target/generated-sources/annotations">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="ignore_optional_problems" value="true"/>
<attribute name="m2e-apt" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="target/generated-test-sources/test-annotations">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="ignore_optional_problems" value="true"/>
<attribute name="m2e-apt" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
差异被折叠。
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.zrqx.system</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.genuitec.eclipse.springframework.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.boot.validation.springbootbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>com.genuitec.eclipse.springframework.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding//src/test/resources=UTF-8
encoding/<project>=UTF-8
eclipse.preferences.version=1
org.eclipse.jdt.apt.aptEnabled=true
org.eclipse.jdt.apt.genSrcDir=target\\generated-sources\\annotations
org.eclipse.jdt.apt.genTestSrcDir=target\\generated-test-sources\\test-annotations
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.processAnnotations=enabled
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
<root>
<facet id="me.spring">
<node name="libprov">
<attribute name="provider-id" value="spring-no-op-library-provider"/>
</node>
</facet>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="java" version="1.8"/>
<installed facet="me.spring" version="4.1"/>
</faceted-project>
boot.validation.initialized=true
eclipse.preferences.version=1
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zrqx</groupId>
<artifactId>com.zrqx.pom</artifactId>
<version>4.0.0</version>
<relativePath>../com.zrqx.pom</relativePath>
</parent>
<groupId>com.zrqx.system</groupId>
<artifactId>com.zrqx.system</artifactId>
<dependencies>
<dependency>
<groupId>com.zrqx</groupId>
<artifactId>com.zrqx.core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--表示为web工程 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 用于健康监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--熔断器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<!-- <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId>
</dependency> -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--分布式事务 -->
<!-- <dependency> <groupId>com.codingapi</groupId> <artifactId>transaction-springcloud</artifactId>
<exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>*</artifactId>
</exclusion> </exclusions> </dependency> <dependency> <groupId>com.codingapi</groupId>
<artifactId>tx-plugins-db</artifactId> <exclusions> <exclusion> <groupId>org.slf4j</groupId>
<artifactId>*</artifactId> </exclusion> </exclusions> </dependency> -->
<!--swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--用于测试的 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 热部署工具 -->
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId>
</dependency> -->
<!-- fastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- 跨服务调用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.zrqx.system;
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.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 org.springframework.transaction.annotation.EnableTransactionManagement;
import com.alibaba.druid.pool.DruidDataSource;
import tk.mybatis.spring.annotation.MapperScan;
@EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
@EnableFeignClients
@EnableEurekaClient
@EnableHystrix
@EnableHystrixDashboard
@SpringBootApplication // 系统会去入口类的同级包以及下级包中去扫描实体类,因此我们建议入口类的位置在groupId+arctifactID组合的包名下。
@MapperScan(basePackages = {"com.zrqx.system.bg.mapper.*","com.zrqx.system.fg.mapper.*"})
public class SystemStart {
@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(SystemStart.class);
public static void main(String[] args) {
// 下面两行代码都可以用来启动
SpringApplication.run(SystemStart.class, args);
// new SpringApplicationBuilder(AppStart.class).web(true).run(args);
logger.debug("debug:system服务已启动.....");
logger.info("info:system服务已启动.....");
}
@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.system.bg.controller.information;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zrqx.core.constant.system.SystemRequestPath;
import com.zrqx.core.model.system.InformationColumn;
import com.zrqx.core.util.page.PageInfo;
import com.zrqx.core.util.page.PageParam;
import com.zrqx.core.util.response.CallBack;
import com.zrqx.system.bg.service.information.InformationColumnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping(SystemRequestPath.BG + SystemRequestPath.INFORMATIONCOLUMN)
@Api(description = "后台-系统管理-资讯栏目管理")
public class InformationColumnController {
@Autowired
private InformationColumnService service;
@ApiOperation(value = "新增栏目", notes = "新增一条栏目")
@PostMapping(value = SystemRequestPath.SAVE)
public CallBack<Boolean> save(@RequestBody InformationColumn entity) {
return CallBack.success(service.insertSelective(entity));
}
@ApiOperation(value = "查询栏目" , notes = "分页查询栏目")
@GetMapping(value = SystemRequestPath.PAGE )
public CallBack<PageInfo<InformationColumn>> getPageList( PageParam pageParam){
return CallBack.success(service.queryAll(pageParam));
}
@ApiOperation(value = "修改栏目", notes = "修改一条栏目")
@PostMapping(value = SystemRequestPath.UPDATE)
public CallBack<Boolean> update(@RequestBody InformationColumn entity) {
return CallBack.success(service.updateByPrimaryKeySelective(entity));
}
@ApiOperation(value = "删除栏目", notes = "删除一条栏目")
@PostMapping(value = SystemRequestPath.DELETE)
public CallBack<Boolean> delete(String id) {
return CallBack.success(service.deleteByPrimaryKey(id));
}
}
package com.zrqx.system.bg.controller.information;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zrqx.core.constant.system.SystemRequestPath;
import com.zrqx.core.form.system.bg.InformationForm;
import com.zrqx.core.model.system.Information;
import com.zrqx.core.util.page.PageInfo;
import com.zrqx.core.util.page.PageParam;
import com.zrqx.core.util.response.CallBack;
import com.zrqx.system.bg.service.information.InformationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import tk.mybatis.mapper.entity.Example;
@RestController
@RequestMapping(SystemRequestPath.BG + SystemRequestPath.INFORMATION)
@Api(description = "后台-系统管理-资讯管理")
public class InformationController {
@Autowired
private InformationService service;
@ApiOperation(value = "新增资讯", notes = "新增一个")
@PostMapping(value = SystemRequestPath.SAVE)
public CallBack<Boolean> save(@RequestBody Information entity) {
return CallBack.success(service.insertSelective(entity));
}
@ApiOperation(value = "查询资讯" , notes = "分页查询资讯")
@GetMapping(value = SystemRequestPath.PAGE )
public CallBack<PageInfo<Information>> getPageList(InformationForm form, PageParam pageParam){
return CallBack.success(service.queryByCriteria(form,pageParam));
}
@ApiOperation(value = "修改资讯", notes = "修改一条资讯")
@PostMapping(value = SystemRequestPath.UPDATE)
public CallBack<Boolean> update(@RequestBody Information entity) {
return CallBack.success(service.updateByPrimaryKeySelective(entity));
}
@ApiOperation(value = "删除资讯", notes = "删除一条资讯")
@PostMapping(value = SystemRequestPath.DELETE)
public CallBack<Boolean> delete(String id) {
return CallBack.success(service.deleteByPrimaryKey(id));
}
@ApiOperation(value = "置顶资讯", notes = "置顶资讯")
@PostMapping(value = SystemRequestPath.TOP)
public CallBack<Boolean> top(@RequestBody List<String> ids) {
Information information =new Information();
information.setTop(1);
Example example = service.createExample();
example.createCriteria().andIn("id", ids);
return CallBack.success(service.UpdateByExampleSelective(information, example));
}
@ApiOperation(value = "取消置顶资讯", notes = "取消置顶资讯")
@PostMapping(value = SystemRequestPath.UNTOP)
public CallBack<Boolean> uptop(@RequestBody List<String> ids) {
Information information =new Information();
information.setTop(0);
Example example = service.createExample();
example.createCriteria().andIn("id", ids);
return CallBack.success(service.UpdateByExampleSelective(information, example));
}
}
package com.zrqx.system.bg.mapper.information;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.system.InformationColumn;
public interface InformationColumnMapper extends BaseMapper<InformationColumn> {
}
package com.zrqx.system.bg.mapper.information;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.system.Information;
public interface InformationMapper extends BaseMapper<Information> {
}
package com.zrqx.system.bg.service.information;
import com.zrqx.core.model.system.InformationColumn;
import com.zrqx.core.service.BaseService;
public interface InformationColumnService extends BaseService<InformationColumn,String>{
}
package com.zrqx.system.bg.service.information;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.system.InformationColumn;
import com.zrqx.core.service.BaseServiceImpl;
import com.zrqx.system.bg.mapper.information.InformationColumnMapper;
/**
* 自定义分类
*/
@Service
public class InformationColumnServiceImpl extends BaseServiceImpl<InformationColumn,String> implements InformationColumnService {
@Autowired
private InformationColumnMapper mapper;
@Override
public BaseMapper<InformationColumn> getMapper() {
return mapper;
}
}
package com.zrqx.system.bg.service.information;
import com.zrqx.core.form.system.bg.InformationForm;
import com.zrqx.core.model.system.Information;
import com.zrqx.core.service.BaseService;
import com.zrqx.core.util.page.PageInfo;
import com.zrqx.core.util.page.PageParam;
public interface InformationService extends BaseService<Information,String>{
PageInfo<Information> queryByCriteria(InformationForm form, PageParam pageParam);
}
package com.zrqx.system.bg.service.information;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zrqx.core.form.system.bg.InformationForm;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.system.Information;
import com.zrqx.core.service.BaseServiceImpl;
import com.zrqx.core.util.page.PageInfo;
import com.zrqx.core.util.page.PageParam;
import com.zrqx.system.bg.mapper.information.InformationMapper;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
/**
* 自定义分类
*/
@Service
public class InformationServiceImpl extends BaseServiceImpl<Information,String> implements InformationService {
@Autowired
private InformationMapper mapper;
@Override
public BaseMapper<Information> getMapper() {
return mapper;
}
@Override
public PageInfo<Information> queryByCriteria(InformationForm form, PageParam pageParam) {
if (null != pageParam && StringUtils.isBlank(pageParam.getOrderBy())) {
pageParam.setOrderBy("createTime desc");
}
Example example = new Example(Information.class);
Criteria createCriteria = example.createCriteria();
if (form != null) {
if (StringUtils.isNotBlank(form.getTitle())) {
createCriteria.andLike("title", "%"+form.getTitle()+"%");
}
if (StringUtils.isNotBlank(form.getBeginTime())) {
createCriteria.andGreaterThanOrEqualTo("publishTime", form.getBeginTime()+" 00:00:00");
}
if (StringUtils.isNotBlank(form.getEndTime())) {
createCriteria.andLessThanOrEqualTo("publishTime", form.getEndTime()+" 23:59:59");
}
}
return queryExample(pageParam,example);
}
}
package com.zrqx.system.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.system.commons.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
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() {
//添加head参数start
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("y-token").description("y令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
tokenPar.name("x-token").description("x令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
//添加head参数end
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.zrqx"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars);
}
//构建 api文档的详细信息函数
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("system 测试使用 Swagger2 构建RESTful API")
//描述
.description("system服务 API 描述")
//创建人
.contact(new Contact("陈新昌", "www.baidu.com", "cxinchang@126.com"))
//版本号
.version("3.0")
.build();
}
}
\ No newline at end of file
package com.zrqx.system.commons.config;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.support.FormattingConversionServiceFactoryBean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.zrqx.core.constant.system.SystemRequestPath;
import com.zrqx.system.commons.convert.StringToDateConverter;
import com.zrqx.system.commons.interceptor.InterceptorConfig;
/**
* 使用CustomWebMvcConfigurationSupport来显对 mvc的配置
* @author lpf
* @date 2018年7月24日下午8:01:05
*/
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
/**
* 跨域支持
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowCredentials(false).maxAge(3600);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(fastJsonHttpMessageConverter());
super.configureMessageConverters(converters);
}
@Bean
public HttpMessageConverter<Object> fastJsonHttpMessageConverter(){
// fastjson 转换器
FastJsonHttpMessageConverter fast = new FastJsonHttpMessageConverter();
// fastjson 配置
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
// DisableCircularReferenceDetect 关闭循环引用检测 ,作用: 引用序列化不彻底时
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat, SerializerFeature.QuoteFieldNames,
SerializerFeature.DisableCircularReferenceDetect);
fast.setFastJsonConfig(fastJsonConfig);
// fastJson 支持解析类型
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.APPLICATION_JSON_UTF8);
fast.setSupportedMediaTypes(list);
return fast;
}
@Bean
public Converter<String, Date> stringToDateConverter() {
StringToDateConverter conver = new StringToDateConverter();
return conver;
}
@Bean
public FormattingConversionServiceFactoryBean conversionService() {
FormattingConversionServiceFactoryBean bean = new FormattingConversionServiceFactoryBean();
Set<Converter<?, ?>> set = new HashSet<Converter<?, ?>>();
set.add(stringToDateConverter());
bean.setConverters(set);
return bean;
}
public ConfigurableWebBindingInitializer webBindingInitializer(@Autowired ConfigurableWebBindingInitializer config) {
config.setConversionService(conversionService().getObject());
return config;
}
}
\ No newline at end of file
package com.zrqx.system.commons.convert;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class MappingFastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private SerializerFeature[] serializerFeature;
public SerializerFeature[] getSerializerFeature() {
return serializerFeature;
}
public void setSerializerFeature(SerializerFeature[] serializerFeature) {
this.serializerFeature = serializerFeature;
}
public MappingFastJsonHttpMessageConverter() {
super(new MediaType("application", "json", DEFAULT_CHARSET));
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return true;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return true;
}
@Override
protected boolean supports(Class<?> clazz) {
throw new UnsupportedOperationException();
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = inputMessage.getBody().read()) != -1) {
baos.write(i);
}
return JSON.parseObject(baos.toString(), clazz);
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
String jsonString = JSON.toJSONString(o, serializerFeature);
OutputStream out = outputMessage.getBody();
out.write(jsonString.getBytes(DEFAULT_CHARSET));
out.flush();
}
}
package com.zrqx.system.commons.convert;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* 字符串转换为Date
* @author lpf
* @date 2018年7月10日下午4:02:01
*/
@Component
public class StringToDateConverter implements Converter<String, Date> {
private static final List<String> formarts = new ArrayList<String>(4);
static{
formarts.add("yyyy-MM");
formarts.add("yyyy-MM-dd");
formarts.add("yyyy-MM-dd hh:mm");
formarts.add("yyyy-MM-dd HH:mm:ss");
}
public Date convert(String source) {
String value = source.trim();
if ("".equals(value)) {
return null;
}
if(source.matches("^\\d{4}-\\d{1,2}$")){
return parseDate(source, formarts.get(0));
}else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
return parseDate(source, formarts.get(1));
}else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
return parseDate(source, formarts.get(2));
}else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
return parseDate(source, formarts.get(3));
}else {
throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
}
}
public Date parseDate(String dateStr, String format) {
Date date=null;
try {
DateFormat dateFormat = new SimpleDateFormat(format);
date = (Date) dateFormat.parse(dateStr);
} catch (Exception e) {
}
return date;
}
}
package com.zrqx.system.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.enums.ResponseCodeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.exception.BusinessValidateException;
import com.zrqx.core.exception.LoginValidateException;
import com.zrqx.core.exception.ParameterValidateException;
import com.zrqx.core.util.response.CallBack;
/**
*controller 异常处理
* @ClassName: CustomExceptionHandler
* @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) {
if(e.getCode() != 0){
return CallBack.fail(e.getCode(),null,e.getMessage());
}
return CallBack.fail(ResponseCodeEnum.EXCEPTION.getCode(),null,e.getMessage());
}
/**
* 业务验证异常
* @param e
* @return
* @author ycw
* @date: 2018年12月26日 上午9:22:33
*/
@ExceptionHandler(BusinessValidateException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object myException(BusinessValidateException e) {
if(e.getCode() != 0){
return CallBack.fail(e.getCode(),null,e.getMessage());
}
return CallBack.fail(ResponseCodeEnum.FAIL.getCode(),null,e.getMessage());
}
/**
* 参数验证异常
* @param e
* @return
* @author ycw
* @date: 2018年12月26日 上午9:22:33
*/
@ExceptionHandler(ParameterValidateException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object myException(ParameterValidateException e) {
if(e.getCode() != 0){
return CallBack.fail(e.getCode(),null,e.getMessage());
}
return CallBack.fail(ResponseCodeEnum.VALIDATE.getCode(),null,e.getMessage());
}
/**
* 登陆验证异常
* @param e
* @return
* @author ycw
* @date: 2018年12月26日 上午9:22:33
*/
@ExceptionHandler(LoginValidateException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object myException(LoginValidateException e) {
if(e.getCode() != 0){
return CallBack.fail(e.getCode(),null,e.getMessage());
}
return CallBack.fail(ResponseCodeEnum.NO_LOGIN.getCode(),null,e.getMessage());
}
}
\ No newline at end of file
package com.zrqx.system.commons.interceptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
@Component
public class CustomRequestInterceptor implements RequestInterceptor {
@Autowired
private ObjectMapper objectMapper;
@Override
public void apply(RequestTemplate template) {
// feign 不支持 GET 方法传 POJO, json body转query
if (template.method().equals("GET") && template.body() != null) {
try {
JsonNode jsonNode = objectMapper.readTree(template.body());
template.body(null);
Map<String, Collection<String>> queries = new HashMap<>();
buildQuery(jsonNode, "", queries);
template.queries(queries);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void buildQuery(JsonNode jsonNode, String path, Map<String, Collection<String>> queries) {
if (!jsonNode.isContainerNode()) { // 叶子节点
if (jsonNode.isNull()) {
return;
}
Collection<String> values = queries.get(path);
if (null == values) {
values = new ArrayList<>();
queries.put(path, values);
}
values.add(jsonNode.asText());
return;
}
if (jsonNode.isArray()) { // 数组节点
Iterator<JsonNode> it = jsonNode.elements();
while (it.hasNext()) {
buildQuery(it.next(), path, queries);
}
} else {
Iterator<Map.Entry<String, JsonNode>> it = jsonNode.fields();
while (it.hasNext()) {
Map.Entry<String, JsonNode> entry = it.next();
if (StringUtils.hasText(path)) {
buildQuery(entry.getValue(), path + "." + entry.getKey(), queries);
} else { // 根节点
buildQuery(entry.getValue(), entry.getKey(), queries);
}
}
}
}
}
package com.zrqx.system.commons.interceptor;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import feign.RequestInterceptor;
import feign.RequestTemplate;
/**
* Feign配置
* 使用FeignClient进行服务间调用,传递headers信息
* @author lw
* @date 2018年10月17日下午2:48:44
*/
@Component
public class FeignHeaderInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
// 前台token
if(request.getHeader("Y-Token") != null){
requestTemplate.header("Y-Token", request.getHeader("Y-Token"));
}
// 后台token
if(request.getHeader("X-Token") != null){
requestTemplate.header("X-Token", request.getHeader("X-Token"));
}
}
}
}
package com.zrqx.system.commons.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class InterceptorConfig implements HandlerInterceptor{
private static final Logger logger = LoggerFactory.getLogger(InterceptorConfig.class);
/**
* 进入controller层之前拦截请求
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
HttpSession session = httpServletRequest.getSession();
if(session.getAttribute("user") != null){
return true;
}
else{
// PrintWriter printWriter = httpServletResponse.getWriter();
// printWriter.write(JsonUtil.bean2Json(CallBack.create(ResponseCodeEnum.NO_LOGIN)));
// return false;
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}
\ No newline at end of file
package com.zrqx.system.commons.redis;
import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSON;
import com.zrqx.core.enums.ResponseCodeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.sysuser.fg.user.LoginUserInfo;
import com.zrqx.core.model.sysuser.user.User;
import com.zrqx.core.util.JsonUtil.JsonUtil;
/**
* Redis消息管理 ,调用时不能用多线程调用
* @author lpf
* @date 2018年6月5日上午10:03:01
*/
@Component
public class Redis {
private static final Logger logger = LoggerFactory.getLogger(Redis.class);
private static final String FG_TOKEN = "y-token";
private static final String BG_TOKEN = "x-token";
@Autowired
StringRedisTemplate stringRedisTemplate;
/**
* redis 1.0 动态变更数据库
*/
public void updateDatebase(int num) {
JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory();
jedisConnectionFactory.setDatabase(num);
stringRedisTemplate.setConnectionFactory(jedisConnectionFactory);
}
/**
* 获取后台登录用户信息
*
* @return
*/
public User getUser() {
return getInfoObjectRedis(getBgToken(), User.class);
}
/**
* 获取前台登录用户信息
*
* @return
*/
public LoginUserInfo getMember() {
return getInfoObjectRedis(getFgToken(), LoginUserInfo.class);
}
public boolean isExistMember() {
try {
String token = getToken(FG_TOKEN);
String userInfo = get(token);
return StringUtils.isNotEmpty(userInfo);
} catch (Exception e) {
logger.info("未登录");
}
return false;
}
public String fmtObj(Object obj) throws IOException {
return obj instanceof String ? obj.toString():JsonUtil.bean2Json(obj);
}
/**
* 添加到redis
* @param token
* Key
* @param obj
* Value
* @param timeout
* 过期时间
* @param unit
* TimeUnitEnum 时间格式
* @throws IOException
*/
public void set(String token, Object obj, long timeout,TimeUnit unit) throws IOException {
stringRedisTemplate.opsForValue().set(token,fmtObj(obj),timeout,unit);
}
public void set(String token, Object obj, long timeout) throws IOException {
stringRedisTemplate.opsForValue().set(token,fmtObj(obj),timeout,TimeUnit.SECONDS);
}
/**
* 添加到redis
* @param token Key
* @param obj Value
* @throws IOException
*/
public void set(String token,Object obj) throws IOException{
stringRedisTemplate.opsForValue().set(token,fmtObj(obj));
}
/**
* 根据key删除redis中的数据
* @param key
* @throws IOException
*/
public void delete(String key) throws IOException{
stringRedisTemplate.delete(key);
}
/**
* 根据key查询redis中的数据
*
* @param token
* @return
*/
public String get(String token) {
return stringRedisTemplate.opsForValue().get(token);
}
public <T> T getInfoObjectRedis(String key,Class<T> objClass){
try {
String userInfo = get(key);
if(StringUtils.isEmpty(userInfo)) {
throw new BaseException(ResponseCodeEnum.NO_LOGIN);
}
return JSON.parseObject(userInfo, objClass);
} catch (Exception e) {
throw new BaseException("获取用户信息错误!"+e.getMessage());
}
}
public static String getToken(String tokenName){
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
String token = null;
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
//TODO--前台获取token
if(key.toLowerCase().equals(tokenName)){
token=request.getHeader(key);
}
}
if (token == null) {
throw new BaseException(ResponseCodeEnum.NO_LOGIN);
}
return token;
}
public static String getBgToken(){
return getToken(BG_TOKEN);
}
public static String getFgToken(){
return getToken(FG_TOKEN);
}
}
package com.zrqx.system.commons.utils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}
\ No newline at end of file
package com.zrqx.system.commons.utils;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import com.zrqx.core.exception.BaseException;
public class Copy {
/**
* 批量复制对象
*
* @param list
* @param clazz
* @return
*/
public static <VO, R> List<VO> copyList(List<R> list, Class<VO> clazz) {
return list.stream().map(obj -> {
VO vo = null;
try {
vo = clazz.newInstance();
BeanUtils.copyProperties(obj, vo);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
throw new BaseException("批量复制对象时创建对象失败。");
}
return vo;
}).collect(Collectors.toList());
}
/**
* 过滤批量复制对象
*
* @param list
* @param clazz
* @param filter
* @return
*/
public static <VO, R> List<VO> copyList(List<R> list, Class<VO> clazz, Predicate<R> filter) {
return list.stream().filter(filter).map(obj -> {
VO vo = null;
try {
vo = clazz.newInstance();
BeanUtils.copyProperties(obj, vo);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
throw new BaseException("批量复制对象时创建对象失败。");
}
return vo;
}).collect(Collectors.toList());
}
}
package com.zrqx.system.commons.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import javax.servlet.ServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpHelper {
/**
* 获取请求Body
* @param request
* @return
*/
private static Logger logger = LoggerFactory.getLogger(HttpHelper.class);
public static String getBodyString(ServletRequest request) {
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = request.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
logger.warn("getBodyString出现问题!");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
\ No newline at end of file
package com.zrqx.system.commons.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
private ApplicationContext applicationContext; // Spring应用上下文环境
/*
* 实现了ApplicationContextAware 接口,必须实现该方法;
*通过传递applicationContext参数初始化成员变量applicationContext
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return this.applicationContext;
}
/**
* @param beanName bean Id
* @return 如果获取失败,则返回Null
* 功能:通过BeanId获取Spring管理的对象
*/
public Object getObject(String beanName) {
Object object = null;
try {
object = applicationContext.getBean(beanName);
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
/**
* @param clazz 要获取的Bean类
* @return 如果获取失败,则返回Null
* 功能:通过类获取Spring管理的对象
*/
public <T> T getObject(Class<T> clazz) {
try {
return applicationContext.getBean(clazz);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
<link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>
<!--国际化操作:选择中文版 -->
<script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png"><span class="logo__title">swagger</span></a>
<form id='api_selector'>
<div class='input'>
<select id="select_baseUrl" name="select_baseUrl"></select>
</div>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div id='auth_container'></div>
<div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
</form>
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
mybatis:
type-aliases-package: com.zrqx.core.model
mapper:
mappers:
- com.zrqx.core.mapper.BaseMapper
not-empty: false
i-d-e-n-t-i-t-y: MYSQL
style: normal
b-e-f-o-r-e: true
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
spring:
main:
allow-bean-definition-overriding: true #2.1.0 多个接口上的@FeignClient(“相同服务名”)会报错 ,允许覆盖
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
http:
multipart:
maxFileSize: 20Mb
maxRequestSize: 20Mb
feign:
hystrix:
enabled: true
ribbon:
ConnectTimeout: 60000
ReadTimeout: 60000
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE
thread:
timeoutInMilliseconds: 120000
\ No newline at end of file
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>package</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>*.yml</include>
<include>*.xml</include>
<include>static/**</include>
<include>templates/**</include>
<include>*.properties</include>
<include>*.txt</include>
</includes>
<filtered>true</filtered>
<outputDirectory>${file.separator}${project.artifactId}</outputDirectory>
</fileSet>
<fileSet>
<directory>src/main/resources/runScript</directory>
<outputDirectory>${file.separator}${project.artifactId}</outputDirectory>
</fileSet>
<fileSet>
<directory>${project.build.directory}/lib</directory>
<outputDirectory>${file.separator}${project.artifactId}/lib</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
<fileSet>
<directory>${project.build.directory}/</directory>
<outputDirectory>${file.separator}${project.artifactId}</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
server:
port: 8609
spring:
cloud:
config:
uri: http://localhost:8688 #配置中心地址
name: system
profile: prod
label: master
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.padual.com/java/logback.xsd"
debug="false" scan="true" scanPeriod="30 second">
<!--读取配置中心的属性-->
<springProperty scope="context" name="name" source="spring.application.name"/>
<property name="ROOT" value="/opt/logs/syyl/sysuser/" />
<property name="FILESIZE" value="10MB" />
<property name="MAXHISTORY" value="60" />
<property name="DATETIME" value="yyyy-MM-dd HH:mm:ss" />
<!-- 控制台打印 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
</appender>
<!-- ERROR 输入到文件,按日期和文件大小 -->
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/error.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- WARN 输入到文件,按日期和文件大小 -->
<appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/warn.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- INFO 输入到文件,按日期和文件大小 -->
<appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/info.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- DEBUG 输入到文件,按日期和文件大小 -->
<appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/debug.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- TRACE 输入到文件,按日期和文件大小 -->
<appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACE</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/trace.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- SQL相关日志输出-->
<logger name="org.mybatis.spring" level="DEBUG" additivity="true" />
<!-- Logger 根目录 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="DEBUG" />
<appender-ref ref="ERROR" />
<appender-ref ref="WARN" />
<appender-ref ref="INFO" />
<appender-ref ref="TRACE" />
</root>
</configuration>
\ No newline at end of file
@echo off
title %cd%
SET [jarName=[string]]
for %%i in (*.jar) do set jarName=%%i
echo %jarName%
java -Dfile.encoding=UTF-8 -Xmx512m -Xms256m -Xmn64m -Xss64m -jar -Dloader.path=lib %jarName%
\ No newline at end of file
#!/bin/sh
port=8604
jar='.jar'
for fileName in `ls`; do
if [[ $fileName == *$jar* ]]; then
echo $fileName
jarName=$fileName;
break
fi
done
#pid=$(ps -ef | grep $jarName | grep -v grep | awk '{print $2}');
pid=$(netstat -nlp | grep :$port | awk '{print $7}' | awk -F"/" '{print $1}');
echo "server process is $pid"
if [ -n '$pid' ]; then
echo "shut down server service process $pid "
kill -9 $pid;
echo "shut down server service process $pid success"
fi
echo "开始启动 ${jarName}..."
echo "java -jar -Xms50m -Xmx200m $jarName> log.log 2>&1 &"
nohup java -jar -Xms50m -Xmx200m $jarName> log.log 2>&1 &
echo "${jarName}启动成功!"
@echo off
set port=8604
for /f "tokens=5" %%i in ('netstat -aon ^| findstr ":%port%"') do (
set n=%%i
)
taskkill /f /pid %n%
goto %a%
\ No newline at end of file
#!/bin/sh
port=8604
jar='.jar'
for fileName in `ls`; do
if [[ $fileName == *$jar* ]]; then
echo $fileName
jarName=$fileName;
break
fi
done
#pid=$(ps -ef | grep $jarName | grep -v grep | awk '{print $2}');
pid=$(netstat -nlp | grep :$port | awk '{print $7}' | awk -F"/" '{print $1}');
echo "server process is $pid"
if [ -n '$pid' ]; then
echo "shut down server service process $pid "
kill -9 $pid;
echo "shut down server service process $pid success"
fi
echo "${jarName}关闭成功!"
Manifest-Version: 1.0
Implementation-Title: com.zrqx.system
Implementation-Version: 4.0.0
Built-By: Administrator
Implementation-Vendor-Id: com.zrqx.system
Build-Jdk: 1.8.0_152
Implementation-URL: https://projects.spring.io/spring-boot/#/spring-bo
ot-starter-parent/com.zrqx.pom/com.zrqx.system
Created-By: Maven Integration for Eclipse
#Generated by Maven Integration for Eclipse
#Wed Feb 26 11:06:47 CST 2020
version=4.0.0
groupId=com.zrqx.system
m2e.projectName=com.zrqx.system
m2e.projectLocation=D\:\\work\\workspace\\workspacesyyl\\com.zrqx.system
artifactId=com.zrqx.system
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zrqx</groupId>
<artifactId>com.zrqx.pom</artifactId>
<version>4.0.0</version>
<relativePath>../com.zrqx.pom</relativePath>
</parent>
<groupId>com.zrqx.system</groupId>
<artifactId>com.zrqx.system</artifactId>
<dependencies>
<dependency>
<groupId>com.zrqx</groupId>
<artifactId>com.zrqx.core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--表示为web工程 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 用于健康监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--熔断器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<!-- <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId>
</dependency> -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--分布式事务 -->
<!-- <dependency> <groupId>com.codingapi</groupId> <artifactId>transaction-springcloud</artifactId>
<exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>*</artifactId>
</exclusion> </exclusions> </dependency> <dependency> <groupId>com.codingapi</groupId>
<artifactId>tx-plugins-db</artifactId> <exclusions> <exclusion> <groupId>org.slf4j</groupId>
<artifactId>*</artifactId> </exclusion> </exclusions> </dependency> -->
<!--swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--用于测试的 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 热部署工具 -->
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId>
</dependency> -->
<!-- fastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- 跨服务调用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
#Generated by Maven Integration for Eclipse
#Wed Feb 26 11:03:11 CST 2020
version=4.0.0
groupId=com.zrqx.sysuser
m2e.projectName=com.zrqx.system
m2e.projectLocation=D\:\\work\\workspace\\workspacesyyl\\com.zrqx.system
artifactId=com.zrqx.sysuser
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zrqx</groupId>
<artifactId>com.zrqx.pom</artifactId>
<version>4.0.0</version>
<relativePath>../com.zrqx.pom</relativePath>
</parent>
<groupId>com.zrqx.sysuser</groupId>
<artifactId>com.zrqx.sysuser</artifactId>
<dependencies>
<dependency>
<groupId>com.zrqx</groupId>
<artifactId>com.zrqx.core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--表示为web工程 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 用于健康监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--熔断器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<!-- <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId>
</dependency> -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--分布式事务 -->
<!-- <dependency> <groupId>com.codingapi</groupId> <artifactId>transaction-springcloud</artifactId>
<exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>*</artifactId>
</exclusion> </exclusions> </dependency> <dependency> <groupId>com.codingapi</groupId>
<artifactId>tx-plugins-db</artifactId> <exclusions> <exclusion> <groupId>org.slf4j</groupId>
<artifactId>*</artifactId> </exclusion> </exclusions> </dependency> -->
<!--swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--用于测试的 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 热部署工具 -->
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId>
</dependency> -->
<!-- fastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- 跨服务调用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
<link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>
<!--国际化操作:选择中文版 -->
<script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png"><span class="logo__title">swagger</span></a>
<form id='api_selector'>
<div class='input'>
<select id="select_baseUrl" name="select_baseUrl"></select>
</div>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div id='auth_container'></div>
<div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
</form>
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
mybatis:
type-aliases-package: com.zrqx.core.model
mapper:
mappers:
- com.zrqx.core.mapper.BaseMapper
not-empty: false
i-d-e-n-t-i-t-y: MYSQL
style: normal
b-e-f-o-r-e: true
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
spring:
main:
allow-bean-definition-overriding: true #2.1.0 多个接口上的@FeignClient(“相同服务名”)会报错 ,允许覆盖
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
http:
multipart:
maxFileSize: 20Mb
maxRequestSize: 20Mb
feign:
hystrix:
enabled: true
ribbon:
ConnectTimeout: 60000
ReadTimeout: 60000
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE
thread:
timeoutInMilliseconds: 120000
\ No newline at end of file
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>package</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>*.yml</include>
<include>*.xml</include>
<include>static/**</include>
<include>templates/**</include>
<include>*.properties</include>
<include>*.txt</include>
</includes>
<filtered>true</filtered>
<outputDirectory>${file.separator}${project.artifactId}</outputDirectory>
</fileSet>
<fileSet>
<directory>src/main/resources/runScript</directory>
<outputDirectory>${file.separator}${project.artifactId}</outputDirectory>
</fileSet>
<fileSet>
<directory>${project.build.directory}/lib</directory>
<outputDirectory>${file.separator}${project.artifactId}/lib</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
<fileSet>
<directory>${project.build.directory}/</directory>
<outputDirectory>${file.separator}${project.artifactId}</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
server:
port: 8609
spring:
cloud:
config:
uri: http://localhost:8688 #配置中心地址
name: system
profile: prod
label: master
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.padual.com/java/logback.xsd"
debug="false" scan="true" scanPeriod="30 second">
<!--读取配置中心的属性-->
<springProperty scope="context" name="name" source="spring.application.name"/>
<property name="ROOT" value="/opt/logs/syyl/sysuser/" />
<property name="FILESIZE" value="10MB" />
<property name="MAXHISTORY" value="60" />
<property name="DATETIME" value="yyyy-MM-dd HH:mm:ss" />
<!-- 控制台打印 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
</appender>
<!-- ERROR 输入到文件,按日期和文件大小 -->
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/error.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- WARN 输入到文件,按日期和文件大小 -->
<appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/warn.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- INFO 输入到文件,按日期和文件大小 -->
<appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/info.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- DEBUG 输入到文件,按日期和文件大小 -->
<appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/debug.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- TRACE 输入到文件,按日期和文件大小 -->
<appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="utf-8">
<pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACE</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${ROOT}%d/trace.%i.log</fileNamePattern>
<maxHistory>${MAXHISTORY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${FILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- SQL相关日志输出-->
<logger name="org.mybatis.spring" level="DEBUG" additivity="true" />
<!-- Logger 根目录 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="DEBUG" />
<appender-ref ref="ERROR" />
<appender-ref ref="WARN" />
<appender-ref ref="INFO" />
<appender-ref ref="TRACE" />
</root>
</configuration>
\ No newline at end of file
@echo off
title %cd%
SET [jarName=[string]]
for %%i in (*.jar) do set jarName=%%i
echo %jarName%
java -Dfile.encoding=UTF-8 -Xmx512m -Xms256m -Xmn64m -Xss64m -jar -Dloader.path=lib %jarName%
\ No newline at end of file
#!/bin/sh
port=8604
jar='.jar'
for fileName in `ls`; do
if [[ $fileName == *$jar* ]]; then
echo $fileName
jarName=$fileName;
break
fi
done
#pid=$(ps -ef | grep $jarName | grep -v grep | awk '{print $2}');
pid=$(netstat -nlp | grep :$port | awk '{print $7}' | awk -F"/" '{print $1}');
echo "server process is $pid"
if [ -n '$pid' ]; then
echo "shut down server service process $pid "
kill -9 $pid;
echo "shut down server service process $pid success"
fi
echo "开始启动 ${jarName}..."
echo "java -jar -Xms50m -Xmx200m $jarName> log.log 2>&1 &"
nohup java -jar -Xms50m -Xmx200m $jarName> log.log 2>&1 &
echo "${jarName}启动成功!"
@echo off
set port=8604
for /f "tokens=5" %%i in ('netstat -aon ^| findstr ":%port%"') do (
set n=%%i
)
taskkill /f /pid %n%
goto %a%
\ No newline at end of file
#!/bin/sh
port=8604
jar='.jar'
for fileName in `ls`; do
if [[ $fileName == *$jar* ]]; then
echo $fileName
jarName=$fileName;
break
fi
done
#pid=$(ps -ef | grep $jarName | grep -v grep | awk '{print $2}');
pid=$(netstat -nlp | grep :$port | awk '{print $7}' | awk -F"/" '{print $1}');
echo "server process is $pid"
if [ -n '$pid' ]; then
echo "shut down server service process $pid "
kill -9 $pid;
echo "shut down server service process $pid success"
fi
echo "${jarName}关闭成功!"
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论