Commit d8f8b8fd by houseme

添加日志记录 以及拦截处理!

parent 4d115eb5
...@@ -29,3 +29,4 @@ build/ ...@@ -29,3 +29,4 @@ build/
### VS Code ### ### VS Code ###
.vscode/ .vscode/
data
\ No newline at end of file
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>bin</id>
<formats>
<format>zip</format>
</formats>
<dependencySets>
<dependencySet>
<useProjectArtifact>false</useProjectArtifact>
<outputDirectory>lib</outputDirectory>
<scope>compile</scope>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<filtered>true</filtered>
<directory>src/main/resources</directory>
<outputDirectory>/configs</outputDirectory>
<excludes>
<exclude>dev/*</exclude>
<exclude>test/*</exclude>
<exclude>pro/*</exclude>
</excludes>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
</fileSet>
<fileSet>
<filtered>true</filtered>
<directory>src/main/resources/${profiles.active}</directory>
<outputDirectory>/configs</outputDirectory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
</fileSet>
<fileSet>
<filtered>true</filtered>
<directory>scripts</directory>
<outputDirectory>/bin</outputDirectory>
</fileSet>
<fileSet>
<directory>target</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
<excludes>
<exclude>*sources.jar</exclude>
</excludes>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
#!/bin/bash
#Current home
CURR_HOME=$(dirname $(readlink -f $0))
#jvm options
JAVA_OPTS="-Xms1g -Xmx1g -Djava.awt.headless=true -XX:MaxPermSize=512m -server -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=85 -Xnoclassgc -Xverify:none -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled"
JAR_FILE="$CURR_HOME/../${artifactId}-${version}.jar"
CMD="nohup java $JAVA_OPTS -jar $JAR_FILE > /dev/null 2>&1 &"
PID_FILE="${providers-path}/${artifactId}/run/${artifactId}-${profiles.active}.pid"
echo $JAR_FILE
###################################
#startup
###################################
start() {
pid=""
if [ -f "$PID_FILE" ]; then
pid=`cat "$PID_FILE"`
fi
if [ "$pid" != "" ] && [ -d "/proc/$pid" ]; then
echo "Process has been started with pid: $pid, ignore."
else
eval "$CMD"
pid=$!
echo "$pid" > "$PID_FILE"
echo "Process started at $pid."
fi
}
###################################
#stop
###################################
stop() {
pid=""
if [ -f "$PID_FILE" ]; then
pid=`cat "$PID_FILE"`
fi
if [ "$pid" == "" ] || [ ! -d "/proc/$pid" ]; then
echo "Process is not running, ignore."
else
echo "Trying to killing process $pid gracefully."
kill -15 $pid > /dev/null 2>&1
sleep 3
if [ -d "/proc/$pid" ]; then
echo "Process still alive, killing it in anger!"
kill -9 $pid > /dev/null 2>&1
fi
echo "Process stopped"
fi
if [ -f "$PID_FILE" ]; then
rm -f $PID_FILE
fi
}
###################################
#status
###################################
status() {
pid=""
if [ -f "$PID_FILE" ]; then
pid=`cat "$PID_FILE"`
fi
if [ "$pid" != "" ] && [ -d "/proc/$pid" ]; then
echo "Process is running! (pid=$pid)"
else
echo "Process is not running"
fi
}
###################################
###################################
#Accept only 1 argument:{start|stop|restart|status}
###################################
case "$1" in
'start')
start
;;
'stop')
stop
;;
'restart')
stop
start
;;
'status')
status
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
esac
exit 0
package com.lanren.huhu.partner; package com.lanren.huhu.partner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author houseme
*/
@SpringBootApplication @SpringBootApplication
public class PartnerApplication { public class PartnerApplication {
public static void main(String[] args) { private static Logger logger = LoggerFactory.getLogger(PartnerApplication.class);
SpringApplication.run(PartnerApplication.class, args);
}
public static void main(String[] args) {
try {
SpringApplication.run(PartnerApplication.class, args);
logger.info("PartnerApplication >>>服务启动成功");
Object lock = new Object();
synchronized (lock) {
try {
while (true) {
lock.wait();
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
} catch (Exception e) {
logger.error("PartnerApplication>>服务启动失败", e);
e.printStackTrace();
}
}
} }
package com.lanren.huhu.partner.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author houseme
* @date 2017/9/8 上午11:54
* Project snacks
* Package com.yinguo.snacks.aspect
* File
*/
@Aspect
@Order(5)
@Component
public class WebLogAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.yinguo.*.controller.*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
//header 部分处理
Map<String, String> map = new HashMap<String, String>();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
logger.info("HEADER :{} ", map.toString());
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
logger.info("RESPONSE : " + ret);
logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
}
}
package com.lanren.huhu.partner.config;
import com.alibaba.fastjson.JSON;
import com.lanren.huhu.partner.constants.CommonStatusConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author houseme
* @date 2019-04-02 21:31
* Project partner
* Package com.lanren.huhu.partner
* File: AuthenticationInterceptor
*/
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
private final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
HandlerMethod handlerMethod = (HandlerMethod) handler;
logger.info("AuthenticationInterceptor Method ==>{}", handlerMethod.getMethod().getName());
logger.info("AuthenticationInterceptor HandlerMethod ==>{}", handlerMethod.getBeanType().getName());
return true;
}
private void returnMsg(HttpServletResponse response) throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("code", CommonStatusConstant.SESSION_TIMEOUT.getValue());
map.put("msg", CommonStatusConstant.SESSION_TIMEOUT.getDesc());
response.setHeader("Content-type", "application/json;charset=UTF-8");
logger.info("msg :{}", CommonStatusConstant.SESSION_TIMEOUT.getDesc());
response.getWriter().write(JSON.toJSONString(map));
}
}
package com.lanren.huhu.partner.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
*
* @author houseme
* @date 2018/12/21
*/
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
package com.lanren.huhu.partner.config;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.cache.annotation.EnableCaching;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author houseme
* @date 2018/1/22 下午11:51
* File
*/
@Configuration
@EnableCaching
public class RedisConfiguration {
@Bean
public RedisCacheManager getRedisCacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheWriter cacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer);
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
return new RedisCacheManager(cacheWriter, cacheConfig);
}
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
//设置默认的Serialize,包含 keySerializer & valueSerializer
redisTemplate.setDefaultSerializer(fastJsonRedisSerializer);
//单独设置valueSerializer
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
//单独设置keySerializer
redisTemplate.setKeySerializer(fastJsonRedisSerializer);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setStringSerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
package com.lanren.huhu.partner.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
/**
* @author houseme
* @date 2019-04-02 21:26
* Project xmb
* Package com.lanren.huhu.partner.config
* File: WebMvcAutoConfiguration
*/
@Configuration
@EnableWebMvc
public class WebMvcAutoConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/v1/**").excludePathPatterns("/v1/init/**");
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
/**
* Configure cross origin requests processing.
*
* @param registry
* @since 4.2
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("POST", "GET", "PUT", "DELETE");
}
/**
* Configure the {@link HttpMessageConverter}s to use for reading or writing
* to the body of the request or response. If no converters are added, a
* default list of converters is registered.
* <p><strong>Note</strong> that adding converters to the list, turns off
* default converter registration. To simply add a converter without impacting
* default registration, consider using the method
* {@link #extendMessageConverters(List)} instead.
*
* @param converters initially an empty list of converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
converter.setSupportedMediaTypes(supportedMediaTypes);
//自定义配置...
FastJsonConfig config = new FastJsonConfig();
//config.set ...
SerializerFeature[] serializerFeatures = new SerializerFeature[]{
SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.QuoteFieldNames, SerializerFeature.WriteBigDecimalAsPlain
};
config.setSerializerFeatures(serializerFeatures);
converter.setFastJsonConfig(config);
converters.add(converter);
// ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
// objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}
}
package com.lanren.huhu.partner.constants;
/**
* 改为枚举值定义
* 由于子项目的代码从10001开始,为避免重复,当前状态码应小于10000。
* MessageCodeLoader初始化时默认先加载当前枚举,然后加载msg.properties配置(实现继承关系:子项目不用再重复定义CommonStatus中已有的状态码)。
* 为避免子项目状态码重复,父类如已经定义,MessageCodeLoader不再加载子项目定义的冲突状态码(CommonStatus优先)。
*
* @author houseme
* @see com.yinguo.xmb.manager
* <p>
* <p>
* <p>
* 约定规则
* provider业务代码都应该在这里定义
* consumer业务代码在msg.properties定义
*/
public enum CommonStatusConstant {
OK(200, "成功!"),
CREATED(201, "已经创建!"),
DEFAULT_BIZ_ERROR(202, "业务异常!(此处应该被具体业务代码重写)"),
BAD_REQUEST(400, "请求失效,请稍后再试!"),
UNAUTHORIZED(401, "未经授权的操作,请联系系统管理员!"),
NOT_FOUND(404, "未找到资源,请稍后再试!"),
METHOD_NOT_ALLOWED(405, "该方法禁止调用,请联系系统管理员!"),
CONFLICT(409, "操作冲突,请稍后再试!"),
SESSION_TIMEOUT(410, "用户信息超时,请重新登录!"),
LOGIN_FAILD(411, "用户名或密码错误!"),
SESSION_REFRESH(412, "Token Refreshed"),
INVALID_PARAMETER(450, "参数验证未通过!"),
PERMISSION_DENIED(452, "权限拒绝,请联系系统管理员!"),
INTERNAL_SERVER_ERROR(500, "服务器内部异常,请稍后再试!"),
NO_REPLY(558, "服务器无应答,请稍后再试!!"),
UNCATCHED_EXCEPTION(553, "未捕获的异常,请稍后再试!"),
ENTITY_NOT_FOUNT(601, "数据未找到,请稍后再试!");
private Integer value;
private String desc;
private CommonStatusConstant(Integer value, String desc) {
this.value = value;
this.desc = desc;
}
public Integer getValue() {
return value;
}
public String getDesc() {
return desc;
}
}
package com.lanren.huhu.partner.manager;
import com.lanren.huhu.partner.constants.CommonStatusConstant;
import com.lanren.huhu.partner.util.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 初始化加载参数到内存中
* <p>
* 部分业务代码依赖CommonStatusConstant
*
* @author houseme
* @see com.lanren.huhu.partner.constants.CommonStatusConstant
*/
@Component
public class MessageCodeLoader {
private static Logger logger = LoggerFactory.getLogger(MessageCodeLoader.class);
public MessageCodeLoader() {
init("conf/msg.properties");
}
public MessageCodeLoader(String resource) {
init(resource);
}
public void init(String resource) {
try {
Properties p = new Properties();
p.load(this.getClass().getClassLoader().getResourceAsStream(resource));
Map<Integer, String> comm_code = toMap(CommonStatusConstant.class);
MessageUtil.putAll(comm_code);
for (Object obj : p.keySet()) {
MessageUtil.put(Integer.parseInt(obj.toString()), p.getProperty(obj.toString()));
}
} catch (IOException e) {
logger.error("init msg error", e);
}
}
public static void main(String[] args) {
MessageCodeLoader loader = new MessageCodeLoader();
loader.init("conf/msg.properties");
System.out.println(MessageUtil.getMsg(200));
}
public static Map<Integer, String> toMap(Class em) {
Map<Integer, String> map = new HashMap<>();
try {
Method m = em.getMethod("getValue");
Method m_ = em.getMethod("getDesc");
Object[] objs = em.getEnumConstants();
for (Object obj : objs) {
Integer k = (Integer) m.invoke(obj);
String v = (String) m_.invoke(obj);
map.put(k, v);
}
} catch (NoSuchMethodException e) {
logger.error("NoSuchMethodException.", e);
} catch (InvocationTargetException e) {
logger.error("InvocationTargetException.", e);
} catch (Exception e) {
logger.error("Exception.", e);
}
return map;
}
}
package com.lanren.huhu.partner.result;
import com.lanren.huhu.partner.util.MessageUtil;
/**
* 封装Controller返回对象
*
* @author houseme
* @version 1.0
* @date 2016年7月18日 上午10:27:00
*/
public class Result<T> {
private int code;
private String message;
private T data;
private Long time;
public Result() {
this.code = 200;
this.message = MessageUtil.getMsg(code);
this.time = System.currentTimeMillis();
}
public Result(T data) {
this.code = 200;
this.message = MessageUtil.getMsg(code);
this.data = data;
this.time = System.currentTimeMillis();
}
public Result(int code) {
this.code = code;
this.message = MessageUtil.getMsg(code);
this.time = System.currentTimeMillis();
}
public Result(int code, String msg) {
this.code = code;
this.message = msg;
this.time = System.currentTimeMillis();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
this.message = MessageUtil.getMsg(code);
this.time = System.currentTimeMillis();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
", time=" + time +
'}';
}
}
# Created by .ignore support plugin (hsz.mobi)
package com.lanren.huhu.partner.service; package com.lanren.huhu.partner.service;
import java.util.List;
import com.lanren.huhu.partner.domain.PartnerAccount;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
public interface PartnerAccountService extends IService<PartnerAccount>{ import com.lanren.huhu.partner.domain.PartnerAccount;
import java.util.List;
/**
* @author houseme
*/
public interface PartnerAccountService extends IService<PartnerAccount> {
/**
* 批量更新
*
* @param list
* @return
*/
int updateBatch(List<PartnerAccount> list); int updateBatch(List<PartnerAccount> list);
/**
* 批量写入
*
* @param list
* @return
*/
int batchInsert(List<PartnerAccount> list); int batchInsert(List<PartnerAccount> list);
int insertOrUpdate(PartnerAccount record); /**
* 更新或新增
*
* @param partnerAccount
* @return
*/
int insertOrUpdate(PartnerAccount partnerAccount);
int insertOrUpdateSelective(PartnerAccount record); /**
* 选择性写入
*
* @param partnerAccount
* @return
*/
int insertOrUpdateSelective(PartnerAccount partnerAccount);
/***
* 根据用户id查询账户信息
* @param userId
* @return
*/
PartnerAccount getOneByUserId(Long userId);
} }
package com.lanren.huhu.partner.service.impl; package com.lanren.huhu.partner.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import com.lanren.huhu.partner.dao.PartnerAccountMapper; import com.lanren.huhu.partner.dao.PartnerAccountMapper;
import com.lanren.huhu.partner.domain.PartnerAccount; import com.lanren.huhu.partner.domain.PartnerAccount;
import com.lanren.huhu.partner.service.PartnerAccountService; import com.lanren.huhu.partner.service.PartnerAccountService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author houseme
*/
@Service @Service
public class PartnerAccountServiceImpl extends ServiceImpl<PartnerAccountMapper, PartnerAccount> implements PartnerAccountService{ public class PartnerAccountServiceImpl extends ServiceImpl<PartnerAccountMapper, PartnerAccount> implements PartnerAccountService {
@Override @Override
public int updateBatch(List<PartnerAccount> list) { public int updateBatch(List<PartnerAccount> list) {
return baseMapper.updateBatch(list); return baseMapper.updateBatch(list);
} }
@Override @Override
public int batchInsert(List<PartnerAccount> list) { public int batchInsert(List<PartnerAccount> list) {
return baseMapper.batchInsert(list); return baseMapper.batchInsert(list);
} }
@Override @Override
public int insertOrUpdate(PartnerAccount record) { public int insertOrUpdate(PartnerAccount record) {
return baseMapper.insertOrUpdate(record); return baseMapper.insertOrUpdate(record);
} }
@Override @Override
public int insertOrUpdateSelective(PartnerAccount record) { public int insertOrUpdateSelective(PartnerAccount record) {
return baseMapper.insertOrUpdateSelective(record); return baseMapper.insertOrUpdateSelective(record);
} }
public PartnerAccount getOne(Long userId){ @Override
public PartnerAccount getOneByUserId(Long userId) {
QueryWrapper<PartnerAccount> queryWrapper = new QueryWrapper(); QueryWrapper<PartnerAccount> queryWrapper = new QueryWrapper();
queryWrapper.eq("user_id", userId); queryWrapper.eq("user_id", userId);
baseMapper.selectCount(queryWrapper); return baseMapper.selectOne(queryWrapper);
return new PartnerAccount();
} }
} }
package com.lanren.huhu.partner.util;
import org.springframework.util.StringUtils;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* @author houseme
*/
public class MessageUtil {
private static Map<Integer, String> cache = new HashMap<Integer, String>();
public static void put(int code, String msg) {
if (cache.containsKey(code)) {
return;
}
cache.put(code, msg);
}
public static void putAll(Map<Integer, String> map) {
cache.putAll(map);
}
public static String getMsg(int code) {
return getMsg(code, "");
}
public static String getMsg(int code, String defaultValue) {
return getMsg(code, null, defaultValue);
}
public static String getMsg(int code, String[] params, String defaultValue) {
return cache.containsKey(code) ? handleParam(cache.get(code), params) : defaultValue;
}
protected static String handleParam(String msg, String[] params) {
if (params == null || params.length == 0) {
return msg;
}
if (StringUtils.isEmpty(msg)) {
return "";
}
MessageFormat mf = new MessageFormat(msg);
mf.setLocale(Locale.CHINESE);
return mf.format(params);
}
}
spring: spring:
datasource: datasource:
#连接MySQL #连接MySQL
url: jdbc:mysql://localhost:3306/socks?useSSL=false url: @mysql.server@?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&allowMultiQueries=true
username: root username: @mysql.username@
password: root password: @mysql.password@
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 5
max-active: 10
min-idle: 5
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
max-open-prepared-statements: 20
validation-query: SELECT 1
validation-query-timeout: 1200000
test-on-borrow: false
test-on-return: false
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
max-evictable-idle-time-millis: 900000
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;keepAlive=true
filters: stat,wall,slf4j
aop-patterns: com.lanren.huhu.partner.service.*
# # 配置StatFilter
filter.stat.db-type: mysql
filter.stat.log-slow-sql: true
filter.stat.slow-sql-millis: 2000
# 配置WallFilter
filter.wall.enabled: true
filter.wall.db-type: mysql
filter.wall.config.delete-allow: true
filter.wall.config.truncate-allow: false
filter.wall.config.drop-table-allow: false
filter.slf4j.enabled: true
filter.slf4j.statement-create-after-log-enabled: false
filter.slf4j.statement-close-after-log-enabled: false
filter.slf4j.result-set-open-after-log-enabled: false
filter.slf4j.result-set-close-after-log-enabled: false
profiles:
active: @profiles.active@
jmx:
default-domain: @project.artifactId@
## Redis 配置
## Redis数据库索引(默认为0)
redis:
database: 12
## Redis测试服务器地址
host: @redis.host@
## Redis测试服务器连接端口
port: 6379
## Redis测试服务器连接密码(默认为空)
password: @redis.password@
## 连接池最大连接数(使用负值表示没有限制)
lettuce:
pool:
max-active: 8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
## 连接池中的最大空闲连接
max-idle: 8
## 连接池中的最小空闲连接
min-idle: 0
shutdown-timeout: 100ms
## 连接超时时间(毫秒)
timeout: 5000ms
http:
encoding:
charset: UTF-8
enabled: true
force: true
converters:
preferred-json-mapper: fastjson
server:
port: 8099
http2:
enabled: true
tomcat:
uri-encoding: UTF-8
mybatis: mybatis:
configuration: configuration:
#配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。 #配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。
map-underscore-to-camel-case: true map-underscore-to-camel-case: true
mybatis-plus:
type-aliases-package: com.lanren.huhu.partner.domain
mapper-locations: classpath:mapper/*.xml
logging: logging:
level: level:
#打印SQL信息 #打印SQL信息
com.hehe.mapper: debug com.hehe.mapper: debug
200=\u6210\u529F
201=\u5DF2\u7ECF\u521B\u5EFA
202=\u4E1A\u52A1\u5F02\u5E38\uFF01\uFF08\u6B64\u5904\u5E94\u8BE5\u88AB\u5177\u4F53\u4E1A\u52A1\u4EE3\u7801\u91CD\u5199\uFF09
400=\u8BF7\u6C42\u5931\u6548\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
401=\u672A\u7ECF\u6388\u6743\u7684\u64CD\u4F5C\uFF0C\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\uFF01
404=\u672A\u627E\u5230\u8D44\u6E90\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
405=\u8BE5\u65B9\u6CD5\u7981\u6B62\u8C03\u7528\uFF0C\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\uFF01
409=\u64CD\u4F5C\u51B2\u7A81\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
410=\u7528\u6237\u4FE1\u606F\u8D85\u65F6\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\uFF01
411=\u7528\u6237\u540D\u6216\u5BC6\u7801\u9519\u8BEF\uFF01
413=\u7528\u6237\u4FE1\u606F\u5F02\u5E38\uFF01
450=\u53C2\u6570\u9A8C\u8BC1\u672A\u901A\u8FC7\uFF01
452=\u6743\u9650\u62D2\u7EDD\uFF0C\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\uFF01
500=\u670D\u52A1\u5668\u5185\u90E8\u5F02\u5E38\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
558=\u670D\u52A1\u5668\u65E0\u5E94\u7B54\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01\uFF01
553=\u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
601=\u6570\u636E\u672A\u627E\u5230\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
60404=\u6682\u65E0\u6570\u636E\uFF01
#\u767B\u5F55\u76F8\u5173
10100=\u8BF7\u9009\u62E9\u6B63\u786E\u7684\u767B\u5F55\u65B9\u5F0F
10101=\u6388\u6743\u767B\u5F55\u5931\u8D25
10102=\u6388\u6743\u767B\u5F55\u5931\u8D25,\u8BF7\u91CD\u65B0\u6388\u6743
10201=\u767B\u5F55\u6765\u6E90\u6682\u4E0D\u652F\u6301
#OpenId \u672A\u7ED1\u5B9A
10202=\u672A\u7ED1\u5B9A
10203=\u7528\u6237\u5DF2\u7ED1\u5B9A\u4E86\u5176\u4ED6\u7684OPENID
#\u8BE5\u624B\u673A\u53F7\u672A\u627E\u5230\u7528\u6237\u4FE1\u606F
10401=\u624B\u673A\u53F7\u7801\u672A\u6CE8\u518C
10402=\u5BC6\u7801\u9519\u8BEF
#\u7528\u6237\u5DF2\u8FDB\u5165\u5C0F\u9ED1\u5C4B
10403=\u7528\u6237\u5DF2\u7981\u7528
#\u8BE5\u624B\u673A\u53F7\u5728\u7CFB\u7EDF\u4E2D\u5DF2\u5B58
10404=\u624B\u673A\u53F7\u7801\u5DF2\u6CE8\u518C
10405=\u624B\u673A\u53F7\u7801\u586B\u5199\u9519\u8BEF
#\u5BC6\u7801\u9700\u5927\u4E8E\u516D\u4F4D
10406=\u5BC6\u7801\u81F3\u5C11\u516D\u4F4D
10407=\u627E\u56DE\u5BC6\u7801\u5931\u8D25
#OpenID \u5DF2\u88AB\u7ED1\u5B9A
10408=\u5FAE\u4FE1\u5DF2\u88AB\u7ED1\u5B9A
#OpenID\u4E0D\u5B58\u5728
10409=\u672A\u7ED1\u5B9A
10410=\u8BF7\u5148\u901A\u8FC7\u627E\u56DE\u5BC6\u7801\u8BBE\u7F6E\u5BC6\u7801
10600=\u53C2\u6570\u4E3A\u7A7A
10601=\u624B\u673A\u53F7\u6216\u5BC6\u7801\u4E3A\u7A7A
10602=\u9A8C\u8BC1\u7801\u4E3A\u7A7A
10603=\u9A8C\u8BC1\u7801\u9519\u8BEF
10801=\u9875\u6570\u9519\u8BEF
10802=\u6BCF\u9875\u6761\u6570\u9519\u8BEF
#ReckonTime \u9519\u8BEF\u4EE3\u7801\uFF08109\u5F00\u5934\uFF09
10900=\u4E8B\u4EF6\u5361id\u9519\u8BEF
10901=\u7528\u6237id\u4E0D\u80FD\u4E3A\u7A7A
10902=\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A
10903=\u7C7B\u522Bid\u9519\u8BEF
10904=\u8BA1\u65F6\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A
10905=\u76EE\u6807\u65F6\u95F4\u4E0D\u80FD\u4E3A\u7A7A
10906=\u63D0\u9192\u65F6\u95F4\u4E0D\u80FD\u4E3A\u7A7A
10907=\u63D0\u9192\u53C2\u6570\u4E0D\u80FD\u4E3A\u7A7A
10908=\u7C7B\u522B\u7EC4\u9519\u8BEF
10909=\u5931\u8D25
10910=\u65E5\u671F\u5FC5\u987B\u5C0F\u4E8E\u5F53\u65E5
10911=\u7F6E\u9876\u53C2\u6570\u9519\u8BEF
10912=\u80CC\u666F\u989C\u8272id\u9519\u8BEF
10913=\u5B57\u4F53\u989C\u8272id\u9519\u8BEF
10914=\u91CD\u590D\u5FAA\u73AF\u53C2\u6570\u9519\u8BEF
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="pattern" value="[%level] %d{yy-MM-dd HH:mm:ss.SSS} [%thread] %logger{50}:%line - %msg%n"/>
<property name="log_file" value="@logfile_path@/@profiles.active@/@artifactId@-@profiles.active@"/>
<property name="MaxHistory" value="15"/><!--日志保留天数-->
<property name="MaxFileSize" value="1024MB"/><!--单个文件大小-->
<property name="totalSizeCap" value="1024MB"/><!--单个文件大小-->
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${pattern}</pattern>
</encoder>
</appender>
<appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${log_file}-info.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<FileNamePattern>${log_file}-info.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<MaxHistory>${MaxHistory}</MaxHistory>
<MaxFileSize>${MaxFileSize}</MaxFileSize>
<totalSizeCap>${totalSizeCap}</totalSizeCap>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
</appender>
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${log_file}-error.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<FileNamePattern>${log_file}-error.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<MaxHistory>${MaxHistory}</MaxHistory>
<MaxFileSize>${MaxFileSize}</MaxFileSize>
<totalSizeCap>${totalSizeCap}</totalSizeCap>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<root level="info">
<appender-ref ref="stdout"/>
<appender-ref ref="info"/>
<appender-ref ref="error"/>
</root>
</configuration>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment