提交 59da49cf authored 作者: yangzhenguang's avatar yangzhenguang

--no commit message

上级 14da8f3a
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry including="**/*.java" 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"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" 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="output" path="target/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.zrqx.talk</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.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/main/resources/application.properties=UTF-8
encoding//src/test/java=UTF-8
encoding//src/test/resources=UTF-8
encoding/<project>=UTF-8
eclipse.preferences.version=1
line.separator=\r\n
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
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.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>
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[3.8.2.me201612231634]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[false]]></enableImports>
<configs>
<config>java:com.zrqx.talk.TalkStart</config>
</configs>
<autoconfigs>
</autoconfigs>
<configSets>
</configSets>
</beansProjectDescription>
<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>1.0.0</version>
<relativePath>../com.zrqx.pom</relativePath>
</parent>
<groupId>com.zrqx.talk</groupId>
<artifactId>com.zrqx.talk</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-eureka</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-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-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>
<!-- Springsecurity给服务端提供安全访问 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</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-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}-${project.version}.${build.number}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>META-INF/**/*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<!-- <compilerArgs> <arg>-bootclasspath</arg> <arg>${env.JAVA_HOME}/jre/lib/rt.jar;${env.JAVA_HOME}/jre/lib/jce.jar;${env.JAVA_HOME}/jre/lib/jsse.jar</arg>
</compilerArgs> -->
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.zrqx.talk;
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.feign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import com.alibaba.druid.pool.DruidDataSource;
import tk.mybatis.spring.annotation.MapperScan;
@EnableFeignClients
@EnableEurekaClient
@EnableHystrixDashboard
@SpringBootApplication // 系统会去入口类的同级包以及下级包中去扫描实体类,因此我们建议入口类的位置在groupId+arctifactID组合的包名下。
@MapperScan(basePackages = {"com.zrqx.talk.bg.mapper","com.zrqx.talk.fg.mapper"})
public class TalkStart {
@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(TalkStart.class);
public static void main(String[] args) {
// 下面两行代码都可以用来启动
SpringApplication.run(TalkStart.class, args);
// new SpringApplicationBuilder(AppStart.class).web(true).run(args);
logger.info("talk服务已启动.....");
}
@Bean
public DruidDataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);// 用户名
dataSource.setPassword(password);// 密码
dataSource.setInitialSize(2);
dataSource.setMaxActive(20);
dataSource.setMinIdle(0);
dataSource.setMaxWait(60000);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(false);
dataSource.setTestWhileIdle(true);
dataSource.setPoolPreparedStatements(false);
return dataSource;
/*
* LCNTransactionDataSource dataSourceProxy = new
* LCNTransactionDataSource();
* dataSourceProxy.setDataSource(dataSource);
* dataSourceProxy.setMaxCount(10); return dataSourceProxy;
*/
}
}
package com.zrqx.talk.bg.controller;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.talk.TalkRequestPath;
import com.zrqx.core.enums.ResponseCodeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.talk.bg.ReplyStatusForm;
import com.zrqx.core.model.talk.Reply;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.util.CallBack;
import com.zrqx.core.util.PageInfo;
import com.zrqx.core.util.PageParam;
import com.zrqx.talk.bg.service.ReplyService;
import com.zrqx.talk.bg.service.TalkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
@RestController
@Api(description = "论坛管理-回复")
@RequestMapping(TalkRequestPath.BG+TalkRequestPath.REPLY)
public class ReplyController {
@Autowired
private ReplyService replyService;
@Autowired
private TalkService talkService;
@ApiOperation(value = "显示隐藏回复", notes = "显示隐藏回复")
@PostMapping(value = TalkRequestPath.STATUS)
public CallBack<Boolean> hideshow(@RequestBody ReplyStatusForm reply) {
Reply entity = new Reply();
entity.setStatus(reply.getStatus());
entity.setId(reply.getId());
if (!replyService.updateByPrimaryKeySelective(entity)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
Reply r = replyService.selectByPrimaryKey(reply.getId());
Talk talk = talkService.selectByPrimaryKey(r.getTalkId());
talk.setReplyNum(reply.getStatus()==1?talk.getReplyNum()+1:talk.getReplyNum()-1);
talkService.updateByPrimaryKeySelective(talk);
return CallBack.success(true);
}
@ApiOperation(value = "查询", notes = "根据主题ID查询回复列表")
@GetMapping(value = TalkRequestPath.OID)
public CallBack<PageInfo<Reply>> replyList(@ApiParam(value = "oid", required = true) @PathVariable Integer oid,PageParam pageParam){
if (null != pageParam && StringUtils.isBlank(pageParam.getOrderBy())) {
pageParam.setOrderBy("createDate desc");
}
Reply reply1 =new Reply();
reply1.setTalkId(oid);
reply1.setHierarchy(1);
PageInfo<Reply> pr = replyService.query(reply1, pageParam);
if(pr.getList()!=null){
for (Reply r : pr.getList()) {
Criteria c2 = replyService.createCriteria();
c2.andEqualTo("parentId", r.getId());
c2.andEqualTo("hierarchy", 2);
List<Reply> replyList2 = replyService.selectByCriteria();
r.setReplyList(replyList2);
}
}
return CallBack.success(pr);
}
}
package com.zrqx.talk.bg.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.talk.TalkRequestPath;
import com.zrqx.core.enums.ResponseCodeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.talk.bg.AddClassForm;
import com.zrqx.core.form.talk.bg.AddHotForm;
import com.zrqx.core.form.talk.bg.QueryTalkForm;
import com.zrqx.core.form.talk.bg.SortTalkForm;
import com.zrqx.core.form.talk.bg.UpdateTalkForm;
import com.zrqx.core.model.sysuser.user.User;
import com.zrqx.core.model.talk.Reply;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.util.CallBack;
import com.zrqx.core.util.PageInfo;
import com.zrqx.core.util.PageParam;
import com.zrqx.core.validate.SaveGroup;
import com.zrqx.core.validate.UpdateGroup;
import com.zrqx.core.vo.talk.StatisticVO;
import com.zrqx.core.vo.talk.TalkListVO;
import com.zrqx.talk.bg.service.ReplyService;
import com.zrqx.talk.bg.service.TalkService;
import com.zrqx.talk.commons.Redis;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
@RestController
@Api(description = "论坛管理-话题")
@RequestMapping(TalkRequestPath.BG + TalkRequestPath.TALK)
public class TalkController {
@Autowired
private Redis redis;
@Autowired
private TalkService talkService;
@Autowired
private ReplyService replyService;
@ApiOperation(value = "获取话题列表", notes = "获取话题列表")
@GetMapping(value = TalkRequestPath.LIST)
public CallBack<PageInfo<TalkListVO>> queryTalkList(QueryTalkForm entity, PageParam pageParam) {
if (null != pageParam && StringUtils.isBlank(pageParam.getOrderBy())) {
pageParam.setOrderBy("sortNum desc, publishDate desc");
}
entity.setEndTime(entity.getEndTime()+" 23:59:59");
return CallBack.success(talkService.queryTalkList(entity, pageParam));
}
@ApiOperation(value = "删除主题", notes = "批量删除主题")
@PostMapping(value = TalkRequestPath.BATCH_DELETE)
public CallBack<Integer> deletes(@ApiParam(value = "主题ID数组", required = true) @RequestBody Integer[] ids) {
Criteria cr = replyService.createCriteria();
cr.andIn("talkId", Arrays.asList(ids));
replyService.deleteByCriteria();
return CallBack.success(talkService.deleteByIds(ids));
}
@ApiOperation(value = "显示隐藏主题", notes = "批量显示隐藏主题")
@PostMapping(value = TalkRequestPath.BATCH_UPDATE_STATUS)
public CallBack<Boolean> hideshow(@Validated(value = UpdateGroup.class) @RequestBody UpdateTalkForm form) {
Criteria cr = talkService.createCriteria();
cr.andIn("id", Arrays.asList(form.getIds()));
Talk entity = new Talk();
entity.setStatus(form.getStatus());
if (!talkService.updateByCriteriaSelective(entity)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
Criteria cr1 = replyService.createCriteria();
cr1.andIn("talkId", Arrays.asList(form.getIds()));
Reply reply =new Reply();
reply.setStatus(form.getStatus());
replyService.updateByCriteriaSelective(reply);
return CallBack.success(true);
}
@ApiOperation(value = "修改排序号", notes = "修改排序号")
@PostMapping(value = TalkRequestPath.SORT)
public CallBack<Boolean> sort(@Validated(value = UpdateGroup.class) @RequestBody SortTalkForm form) {
Talk entity = new Talk();
entity.setSortNum(form.getSortNum());
entity.setId(form.getId());
if (!talkService.updateByPrimaryKeySelective(entity)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
return CallBack.success(true);
}
@ApiOperation(value = "查询", notes = "根据ID查询主题")
@GetMapping(value = TalkRequestPath.OID)
public CallBack<Talk> getById(@ApiParam(value = "oid", required = true) @PathVariable Integer oid) {
Talk entity = talkService.selectByPrimaryKey(oid);
return CallBack.success(entity);
}
@ApiOperation(value = "添加热帖", notes = "添加热帖")
@PostMapping(value = TalkRequestPath.SAVEHOT)
public CallBack<Boolean> saveHot(@Validated(value = SaveGroup.class) @RequestBody AddHotForm entity) {
User user = redis.getUser();
Talk talk = new Talk();
BeanUtils.copyProperties(entity, talk);
talk.setPublishDate(new Date());
talk.setStatus(1);
talk.setTalkType(1);
talk.setPraiseNum(0);
talk.setAuthorName(user.getUserName());
/**初始化数据*/
talk.setReplyNum(0);
talk.setLookNum(0);
talk.setSortNum(0);
talk.setPraiseNum(0);
if (!talkService.insertSelective(talk)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
return CallBack.success();
}
@ApiOperation(value = "添加公开课", notes = "添加公开课")
@PostMapping(value = TalkRequestPath.SAVECLASS)
public CallBack<Boolean> saveClass(@Validated(value = SaveGroup.class) @RequestBody AddClassForm entity) {
User user = redis.getUser();
Talk talk = new Talk();
BeanUtils.copyProperties(entity, talk);
talk.setPublishDate(new Date());
talk.setStatus(1);
talk.setTalkType(2);
/**初始化数据*/
talk.setReplyNum(0);
talk.setLookNum(0);
talk.setSortNum(0);
talk.setPraiseNum(0);
talk.setAuthorName(user.getUserName());
if (!talkService.insertSelective(talk)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
return CallBack.success();
}
@ApiOperation(value = "根据作者id查询提问、回答、获赞、采纳", notes = "根据作者id查询提问、回答、获赞、采纳")
@PostMapping(value = TalkRequestPath.STATISTICNUM)
public CallBack<List<StatisticVO>> getEveryNum( @ApiParam(value = "作者id数组", required = true) @RequestBody Integer[] authorIds) {
List<StatisticVO> statisticList = new ArrayList<StatisticVO>();
for (Integer authorId : authorIds) {
StatisticVO sv = new StatisticVO();
Talk talk = new Talk();
talk.setAuthorId(authorId);
talk.setTalkType(0);
List<Talk> talkList = talkService.select(talk);
// 帖子数
Integer tzNum = talkList.size();
// 点赞数
Integer dzNum = 0;
for (Talk t : talkList) {
Integer parseNum = t.getPraiseNum();
dzNum += parseNum;
}
Reply reply = new Reply();
reply.setReplyerId(authorId);
reply.setHierarchy(1);
reply.setTalkType(0);
List<Reply> replyList = replyService.select(reply);
// 回复数
Integer hfNum = replyList.size();
// 采纳数
Integer cnNum = 0;
for (Reply r : replyList) {
dzNum += r.getPraiseNum();
cnNum += r.getAdopt();
}
sv.setTzNum(tzNum);
sv.setHfNum(hfNum);
sv.setDzNum(dzNum);
sv.setCnNum(cnNum);
sv.setAuthorId(authorId);
statisticList.add(sv);
}
return CallBack.success(statisticList);
}
}
package com.zrqx.talk.bg.mapper;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Reply;
public interface ReplyMapper extends BaseMapper<Reply> {
}
package com.zrqx.talk.bg.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.zrqx.core.form.talk.bg.QueryTalkForm;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.vo.talk.TalkListVO;
public interface TalkMapper extends BaseMapper<Talk> {
@Select("<script>select * from talk where talkType=#{talkType} "
+ "<if test = '" + NOTBLANK + "(keyword)' >"
+ "<if test = 'type==1' >"
+ "and theme like concat(#{keyword},'%') "
+ "</if>"
+ "<if test = 'type==2' >"
+ "and authorName like concat(#{keyword},'%') "
+ "</if>"
+ "</if>"
+ "<if test = 'status !=null' >" + "and status = #{status} "
+ "</if>" + "<if test = '" + NOTBLANK+ "(startTime)' >"
+ "<![CDATA[" + "and publishDate >= #{startTime} "
+ "]]>"
+ "</if>"
+ "<if test = '"
+ NOTBLANK
+ "(endTime)' >" + "<![CDATA[" + "and publishDate <= #{endTime} " + "]]>" + "</if>"
+ "</script>")
List<TalkListVO> queryTalkList(QueryTalkForm queryTalkForm);
@Select("<script>"
+ "delete t,r from talk t left join reply r on t.id =r.talkId where t.id in"
+ "<foreach item='item' index='index' collection='array' open='(' separator=',' close=')'>"
+ "#{item}"
+ "</foreach>"
+ "</script>")
Integer deleteByIds(@Param("array") Integer[] ids);
}
package com.zrqx.talk.bg.service;
import com.zrqx.core.model.talk.Reply;
import com.zrqx.core.service.BaseService;
public interface ReplyService extends BaseService<Reply, Integer> {
}
package com.zrqx.talk.bg.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Reply;
import com.zrqx.core.service.BaseServiceImpl;
import com.zrqx.talk.bg.mapper.ReplyMapper;
/**
* 论坛
* @author Administrator
*
*/
@Service
public class ReplyServiceImpl extends BaseServiceImpl<Reply, Integer> implements ReplyService {
@Autowired
private ReplyMapper replyMapper;
@Override
public BaseMapper<Reply> getMapper() {
return replyMapper;
}
}
package com.zrqx.talk.bg.service;
import com.zrqx.core.form.talk.bg.QueryTalkForm;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.service.BaseService;
import com.zrqx.core.util.PageInfo;
import com.zrqx.core.util.PageParam;
import com.zrqx.core.vo.talk.TalkListVO;
public interface TalkService extends BaseService<Talk, Integer> {
PageInfo<TalkListVO> queryTalkList(QueryTalkForm entity, PageParam pageParam);
Integer deleteByIds(Integer[] ids);
}
package com.zrqx.talk.bg.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.zrqx.core.form.talk.bg.QueryTalkForm;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.service.BaseServiceImpl;
import com.zrqx.core.util.PageInfo;
import com.zrqx.core.util.PageParam;
import com.zrqx.core.vo.talk.TalkListVO;
import com.zrqx.talk.bg.mapper.TalkMapper;
/**
* 论坛
* @author Administrator
*
*/
@Service
public class TalkServiceImpl extends BaseServiceImpl<Talk, Integer> implements TalkService {
@Autowired
private TalkMapper talkMapper;
@Override
public BaseMapper<Talk> getMapper() {
return talkMapper;
}
@Override
public PageInfo<TalkListVO> queryTalkList(QueryTalkForm entity,PageParam pageParam){
PageHelper.startPage(pageParam.getPageNum(),pageParam.getPageSize(), pageParam.getOrderBy());
return new PageInfo<TalkListVO>(talkMapper.queryTalkList(entity));
}
@Override
public Integer deleteByIds(Integer[] ids) {
return talkMapper.deleteByIds(ids);
}
}
package com.zrqx.talk.commons;
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.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.zrqx.core.enums.ResponseCodeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.model.sysuser.member.Member;
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 String FG_TOKEN = "y-token";
private static final String BG_TOKEN = "x-token";
@Autowired
StringRedisTemplate stringRedisTemplate;
public void updateDatebase(int num) {
JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory();
jedisConnectionFactory.setDatabase(num);
stringRedisTemplate.setConnectionFactory(jedisConnectionFactory);
}
/**
* 获取后台登录用户信息
*
* @return
*/
public User getUser() {
return getInfoObjectRedis(getToken(BG_TOKEN), User.class);
}
/**
* 获取前台登录用户信息
*
* @return
*/
public Member getMember() {
return getInfoObjectRedis(getToken(FG_TOKEN), Member.class);
}
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 JsonUtil.json2Bean(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.talk.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();
}
};
}
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 设置缓存过期时间
// rcm.setDefaultExpiration(60);//秒
return rcm;
}
@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.talk.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("talk 测试使用 Swagger2 构建RESTful API")
//描述
.description("talk服务 API 描述")
//创建人
.contact(new Contact("陈新昌", "www.baidu.com", "cxinchang@126.com"))
//版本号
.version("3.0")
.build();
}
}
\ No newline at end of file
package com.zrqx.talk.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.talk.TalkRequestPath;
import com.zrqx.talk.commons.convert.StringToDateConverter;
import com.zrqx.talk.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 addInterceptors(InterceptorRegistry registry) {
// 注册自定义拦截器,添加拦截路径和排除拦截路径
registry.addInterceptor(new InterceptorConfig()).addPathPatterns(TalkRequestPath.BG + "/**")
.excludePathPatterns(TalkRequestPath.BG + TalkRequestPath.PERMISSIONS + TalkRequestPath.LOGIN)
.excludePathPatterns(TalkRequestPath.BG + TalkRequestPath.PERMISSIONS + TalkRequestPath.CODE);
}
@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.talk.commons.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.zrqx.talk.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.talk.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.talk.commons.interceptor;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
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.CallBack;
/**
*controller 异常处理
* @ClassName: CustomExceptionHandler
* @author 杨振广
* @date 2016-7-14 上午9:45:40
*
*/
@ControllerAdvice
public class CustomExceptionHandler {
private static Logger logger = Logger.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("<br/>");
}
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
package com.zrqx.talk.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 log = 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.talk.commons.interceptor;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.RollbackRuleAttribute;
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
* Created by guozp on 2017/8/28.
*/
@Aspect
//@Component 事务依然生效
@Configuration
public class TxAdviceInterceptor {
private static final int TX_METHOD_TIMEOUT = 5;
private static final String AOP_POINTCUT_EXPRESSION = "execution(* com.zrqx..service..*Impl.*(..))";
@Autowired
private PlatformTransactionManager transactionManager;
// 其中 dataSource 框架会自动为我们注入
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public TransactionInterceptor txAdvice() {
NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
/*只读事务,不做更新操作*/
RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
readOnlyTx.setReadOnly(true);
readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED );
/*当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务*/
RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
requiredTx.setRollbackRules(
Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
requiredTx.setTimeout(TX_METHOD_TIMEOUT);
Map<String, TransactionAttribute> txMap = new HashMap<>();
txMap.put("add*", requiredTx);
txMap.put("save*", requiredTx);
txMap.put("insert*", requiredTx);
txMap.put("update*", requiredTx);
txMap.put("delete*", requiredTx);
txMap.put("get*", readOnlyTx);
txMap.put("query*", readOnlyTx);
source.setNameMap( txMap );
TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source);
return txAdvice;
}
@Bean
public Advisor txAdviceAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut, txAdvice());
//return new DefaultPointcutAdvisor(pointcut, txAdvice);
}
}
\ No newline at end of file
package com.zrqx.talk.fg.controller;
import java.io.IOException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zrqx.talk.fg.service.WebSocketServer;
@RestController
@RequestMapping("/checkcenter")
public class CheckCenterController {
//推送数据接口
@RequestMapping("/socket/push/{cid}")
public String pushToWeb(@PathVariable String cid,String message) {
try {
WebSocketServer.sendInfo(message,cid);
} catch (IOException e) {
e.printStackTrace();
return cid+"#"+e.getMessage();
}
return cid;
}
}
package com.zrqx.talk.fg.controller;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zrqx.core.constant.talk.TalkRequestPath;
import com.zrqx.core.enums.ResponseCodeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.talk.fg.AddAdoptForm;
import com.zrqx.core.form.talk.fg.AddReplyForm;
import com.zrqx.core.form.talk.fg.ThumbsUpForm;
import com.zrqx.core.model.sysuser.member.Member;
import com.zrqx.core.model.talk.Reply;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.model.talk.ThumbsUp;
import com.zrqx.core.util.CallBack;
import com.zrqx.core.util.PageInfo;
import com.zrqx.core.util.PageParam;
import com.zrqx.core.validate.SaveGroup;
import com.zrqx.talk.commons.Redis;
import com.zrqx.talk.fg.service.FgReplyService;
import com.zrqx.talk.fg.service.FgTalkService;
import com.zrqx.talk.fg.service.ThumbsUpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
@RestController
@Api(description = "前台论坛回复相关")
@RequestMapping(TalkRequestPath.FG + TalkRequestPath.REPLY)
public class FgReplyController {
@Autowired
private Redis redis;
@Autowired
private FgReplyService replyService;
@Autowired
private FgTalkService talkService;
@Autowired
private ThumbsUpService thumbsUpService;
@ApiOperation(value = "查询一级", notes = "根据主题ID查询一级回复列表")
@GetMapping(value = TalkRequestPath.REPLYLIST)
public CallBack<PageInfo<Reply>> getReplyList(@ApiParam(value = "ID", required = true) @RequestParam Integer oid,PageParam pageParam) {
if (null != pageParam && StringUtils.isBlank(pageParam.getOrderBy())) {
pageParam.setOrderBy("createDate desc");
}
Reply reply = new Reply();
reply.setStatus(1);
reply.setTalkId(oid);
reply.setHierarchy(1);
PageInfo<Reply> pr = replyService.query(reply, pageParam);
for(Reply r :pr.getList()){
ThumbsUp tu = new ThumbsUp();
tu.setMemberId(redis.getMember().getId());
tu.setType(2);
tu.setTalkId(r.getId());
int a = thumbsUpService.selectCount(tu);
if (a > 0) {
r.setPraise(1);
}
}
return CallBack.success(pr);
}
@ApiOperation(value = "查询二级", notes = "根据一级ID查询二级回复列表")
@GetMapping(value = TalkRequestPath.REPLYLIST2)
public CallBack<Reply> getReplyList2(@ApiParam(value = "ID", required = true) @RequestParam Integer oid) {
Reply reply = replyService.selectByPrimaryKey(oid);
Example example = replyService.createExample();
example.orderBy("createDate").desc();
Criteria cr = example.createCriteria();
cr.andEqualTo("parentId", oid);
cr.andEqualTo("hierarchy", 2);
cr.andEqualTo("status", 1);
List<Reply> replyList = replyService.selectByCriteria();
reply.setReplyList(replyList);
return CallBack.success(reply);
}
@ApiOperation(value = "添加回复", notes = "添加回复")
@PostMapping(value = TalkRequestPath.SAVEREPLY)
public CallBack<Boolean> saveReply(@Validated(value = SaveGroup.class) @RequestBody AddReplyForm entity) {
Member member =redis.getMember();
Reply reply = new Reply();
BeanUtils.copyProperties(entity, reply);
reply.setStatus(1);
reply.setCreateDate(new Date());
/** 冗余作者相关信息开始*/
reply.setReplyerId(member.getId());
reply.setImg(member.getImg());
reply.setPhoto(member.getPhoto());
reply.setExpertQualified(member.getExpertQualified());
System.out.println("1111111111111:::::::"+member.getEname());
if(member.getEname()!=null){
reply.setAuthorName(member.getEname());
}else{
reply.setAuthorName(member.getNickname());
}
/** 冗余作者相关信息结束*/
reply.setReplyNum(0);
reply.setPraiseNum(0);
if (!replyService.insertSelective(reply)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
if (entity.getHierarchy() == 1) {
/*
* 话题的回复数加一
*/
Talk talk = talkService.selectByPrimaryKey(entity.getTalkId());
talk.setReplyNum(talk.getReplyNum() == null ? 1 : talk.getReplyNum() + 1);
if (!talkService.updateByPrimaryKeySelective(talk)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
} else {
/*
* 帖子的回复数加一
*/
Reply parentreply = replyService.selectByPrimaryKey(entity.getSubparentId());
parentreply.setReplyNum(parentreply.getReplyNum() == null ? 1 : parentreply.getReplyNum() + 1);
if (!replyService.updateByPrimaryKeySelective(parentreply)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
}
return CallBack.success();
}
@ApiOperation(value = "采纳", notes = "采纳")
@PostMapping(value = TalkRequestPath.ADOPT)
public CallBack<Boolean> adopt(@RequestBody AddAdoptForm aaf) {
Criteria cr = replyService.createCriteria();
cr.andEqualTo("talkId", aaf.getTalkId());
List<Reply> replyList = replyService.selectByCriteria();
for (Reply r : replyList) {
if (aaf.getOid().equals(r.getId())) {
if(r.getAdopt().equals(1)){
r.setAdopt(0);
}else{
r.setAdopt(1);
}
} else {
r.setAdopt(0);
}
if (!replyService.updateByPrimaryKeySelective(r)) {
throw new BaseException(ResponseCodeEnum.FAIL);
}
}
return CallBack.success();
}
@ApiOperation(value = "我的回复列表", notes = "我的回复列表")
@GetMapping(value = TalkRequestPath.MYREPLYLIST)
public CallBack<PageInfo<Reply>> queryReplyList(PageParam pageParam) {
if (null != pageParam && StringUtils.isBlank(pageParam.getOrderBy())) {
pageParam.setOrderBy("createDate desc");
}
Reply reply = new Reply();
reply.setReplyerId(redis.getMember().getId());
reply.setStatus(1);
reply.setTalkType(0);
reply.setHierarchy(1);
PageInfo<Reply> pr = replyService.query(reply, pageParam);
for(Reply r :pr.getList()){
Talk talk=talkService.selectByPrimaryKey(r.getTalkId());
r.setTalk(talk);
}
return CallBack.success(pr);
}
@ApiOperation(value = "点赞", notes = "点赞")
@PostMapping(value = TalkRequestPath.THUMBSUP)
public CallBack<Boolean> thumbsUp(@RequestBody ThumbsUpForm aaf) {
if (aaf.getType() == 1) {
Talk talk = talkService.selectByPrimaryKey(aaf.getOid());
talk.setPraiseNum(talk.getPraiseNum() == null ? 1 : talk.getPraiseNum() + 1);
if (!talkService.updateByPrimaryKeySelective(talk)) {
throw new BaseException(ResponseCodeEnum.FAIL);
} else {
ThumbsUp tu = new ThumbsUp();
tu.setMemberId(redis.getMember().getId());
tu.setType(1);
tu.setTalkId(aaf.getOid());
thumbsUpService.insert(tu);
}
} else {
Reply reply = replyService.selectByPrimaryKey(aaf.getOid());
reply.setPraiseNum(reply.getPraiseNum() == null ? 1 : reply.getPraiseNum() + 1);
if (!replyService.updateByPrimaryKey(reply)) {
throw new BaseException(ResponseCodeEnum.FAIL);
} else {
ThumbsUp tu = new ThumbsUp();
tu.setMemberId(redis.getMember().getId());
tu.setType(2);
tu.setTalkId(aaf.getOid());
thumbsUpService.insert(tu);
}
}
return CallBack.success();
}
}
package com.zrqx.talk.fg.mapper;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Reply;
public interface FgReplyMapper extends BaseMapper<Reply> {
}
package com.zrqx.talk.fg.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.zrqx.core.constant.sysuser.SysUserRequestPath;
import com.zrqx.core.form.talk.bg.QueryTalkForm;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.util.CallBack;
import com.zrqx.core.vo.talk.TalkListVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
public interface FgTalkMapper extends BaseMapper<Talk> {
}
package com.zrqx.talk.fg.mapper;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.ThumbsUp;
public interface ThumbsUpMapper extends BaseMapper<ThumbsUp> {
}
package com.zrqx.talk.fg.service;
import com.zrqx.core.model.talk.Reply;
import com.zrqx.core.service.BaseService;
public interface FgReplyService extends BaseService<Reply, Integer> {
}
package com.zrqx.talk.fg.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Reply;
import com.zrqx.core.service.BaseServiceImpl;
import com.zrqx.talk.bg.mapper.ReplyMapper;
/**
* 论坛
* @author Administrator
*
*/
@Service
public class FgReplyServiceImpl extends BaseServiceImpl<Reply, Integer> implements FgReplyService {
@Autowired
private ReplyMapper replyMapper;
@Override
public BaseMapper<Reply> getMapper() {
return replyMapper;
}
}
package com.zrqx.talk.fg.service;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.service.BaseService;
import com.zrqx.core.util.PageInfo;
import com.zrqx.core.util.PageParam;
public interface FgTalkService extends BaseService<Talk, Integer> {
PageInfo<Talk> queryTalkList(Integer talkType,String keyword, PageParam pageParam);
}
package com.zrqx.talk.fg.service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.zrqx.core.form.talk.bg.QueryTalkForm;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Talk;
import com.zrqx.core.service.BaseServiceImpl;
import com.zrqx.core.util.PageInfo;
import com.zrqx.core.util.PageParam;
import com.zrqx.core.vo.talk.TalkListVO;
import com.zrqx.talk.bg.mapper.TalkMapper;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
/**
* 论坛
*
* @author Administrator
*
*/
@Service
public class FgTalkServiceImpl extends BaseServiceImpl<Talk, Integer> implements FgTalkService {
@Autowired
private TalkMapper talkMapper;
@Override
public BaseMapper<Talk> getMapper() {
return talkMapper;
}
@Override
public PageInfo<Talk> queryTalkList(Integer talkType, String keyword, PageParam pageParam) {
PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getOrderBy());
Criteria cr = this.createCriteria();
cr.andEqualTo("talkType", talkType);
cr.andEqualTo("status", 1);
if (StringUtils.isNotBlank(keyword)) {
cr.andLike("text", "%" + keyword + "%");
}
return new PageInfo<Talk>(this.selectByCriteria());
}
}
package com.zrqx.talk.fg.service;
import com.zrqx.core.model.talk.ThumbsUp;
import com.zrqx.core.service.BaseService;
public interface ThumbsUpService extends BaseService<ThumbsUp, Integer> {
}
package com.zrqx.talk.fg.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.talk.Reply;
import com.zrqx.core.model.talk.ThumbsUp;
import com.zrqx.core.service.BaseServiceImpl;
import com.zrqx.talk.bg.mapper.ReplyMapper;
import com.zrqx.talk.fg.mapper.ThumbsUpMapper;
/**
* 论坛
* @author Administrator
*
*/
@Service
public class ThumbsUpServiceImpl extends BaseServiceImpl<ThumbsUp, Integer> implements ThumbsUpService {
@Autowired
private ThumbsUpMapper thumbsUpMapper;
@Override
public BaseMapper<ThumbsUp> getMapper() {
return thumbsUpMapper;
}
}
package com.zrqx.talk.fg.service;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
<!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>
#################redis基础配置#################
spring.redis.database=1
spring.redis.host=192.168.2.230
spring.redis.password=123456
spring.redis.port=6379
# 连接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000
#################redis线程池设置#################
# 连接池中的最大空闲连接,默认值也是8。
spring.redis.pool.max-idle=500
#连接池中的最小空闲连接,默认值也是0。
spring.redis.pool.min-idle=50
# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.pool.max-active=2000
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
spring.redis.pool.max-wait=1000
# 开启断路器
feign.hystrix.enabled=ture
#################redis哨兵设置#################
# Redis服务器master的名字
#spring.redis.sentinel.master=master8026
# redis-sentinel的配置地址和端口
#spring.redis.sentinel.nodes=10.189.80.25:26379,10.189.80.26:26379,10.189.80.27:26378
#spring.cloud.stream.kafka.binder.brokers=192.168.2.230:9092
#spring.cloud.stream.kafka.binder.zk-nodes=192.168.2.230:2181
#spring.cloud.stream.kafka.binder.minPartitionCount=1
#spring.cloud.stream.kafka.binder.autoCreateTopics=true
#
#
#spring.cloud.stream.bindings.test.destination=test
#spring.cloud.stream.bindings.test.group=group-1
#spring.cloud.stream.bindings.test.consumer.concurrency=1
#spring.cloud.stream.bindings.test.consumer.partitioned=false
#默认密码
default-password=123456
\ No newline at end of file
security:
sessions: always #always设置保存用户状态(内存可能会被占满) stateless设置不保存用户状态
basic:
enabled: false #开启认证
logging:
level:
com.zrqx.talk.bg.mapper: DEBUG
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:
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
server:
port: 8113
spring:
cloud:
config:
uri: http://localhost:8188 #配置中心地址
name: talk
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/zbzd/logs/talk/" />
<property name="FILESIZE" value="50MB" />
<property name="MAXHISTORY" value="100" />
<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 name="com.zrqx.talk" 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
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论