Commit fe90ac28 by levphon

新e盾小程序后端服务

0 parents
Showing 40 changed files with 1733 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-archetype-parent</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<description>Microservice Scaffolding Project Base on Spring Cloud</description>
<artifactId>glsx-rest-app-archetype</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-jwt</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-wechat</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package cn.com.glsx.app;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.app.common.enums;
import lombok.Getter;
@Getter
public enum AuthType {
LOCAL("local"), THIRD("third");
private String type;
AuthType(String type) {
this.type = type;
}
}
package cn.com.glsx.app.common.enums;
import lombok.Getter;
@Getter
public enum LoginType {
NATIVE("native"), WECHAT("wechat"), QQ("qq"), APPLE("apple");
private String type;
LoginType(String type) {
this.type = type;
}
}
package cn.com.glsx.app.common.exception;
import com.glsx.plat.exception.SystemMessage;
import lombok.Getter;
/**
* @author payu
*/
@Getter
public class AppServerException extends RuntimeException {
private int errorCode = SystemMessage.FAILURE.getCode();
public AppServerException(String message) {
super(message);
}
public AppServerException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public static AppServerException of(SystemMessage message) {
return new AppServerException(message.getCode(), message.getMsg());
}
public AppServerException(Throwable cause) {
super(cause);
}
public AppServerException(String message, Throwable cause) {
super(message, cause);
}
}
package cn.com.glsx.app.common.exception;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.BusinessException;
import com.glsx.plat.exception.ExceptionLevel;
import com.glsx.plat.exception.GlobalExceptionHandler;
import com.glsx.plat.exception.SystemMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
/**
* 全局异常处理
*
* @author payu
*/
@Slf4j
@RestControllerAdvice
public class AppServerExceptionHandler extends GlobalExceptionHandler {
@ExceptionHandler(AppServerException.class)
public R handleAdminException(AppServerException e) {
saveException(e, ExceptionLevel.fatal);
return R.error(e.getErrorCode(), e.getMessage());
}
/**
* 引入Feign服务的话
*
* @param e
* @return
*/
// @ExceptionHandler(FeignException.class)
// public R handleFeignException(FeignException e) {
// saveException(e, ExceptionLevel.fatal);
// return R.error(e.status(), e.getMessage());
// }
/**
* Mybatis BindingException
*
* @param e
* @return
*/
@ExceptionHandler(BindingException.class)
public R handleBindingException(BindingException e) {
saveException(e, ExceptionLevel.fatal);
return R.error(e.getMessage());
}
@ExceptionHandler(value = MyBatisSystemException.class)
public R myBatisSystemException(MyBatisSystemException e, HttpServletRequest request) {
Throwable cause = e.getCause();
if (cause instanceof BusinessException) {
return businessExceptionHandler(request, e);
}
log.error("数据存储出错", e);
saveException(e, ExceptionLevel.fatal);
return SystemMessage.DATA_HANDLE_ERROR.result();
}
@Override
protected void saveException(Exception e, ExceptionLevel level) {
// TODO: 2020/10/14 异常入库,对此方法进行aop处理
}
}
package cn.com.glsx.app.modules;
import cn.com.glsx.app.modules.model.AppUser;
import cn.com.glsx.app.modules.model.LoginByAccountBO;
import cn.com.glsx.app.modules.service.LoginService;
import cn.com.glsx.app.modules.service.UserService;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
/**
* @author liuyf
*/
@Slf4j
@RestController
public class LocalLoginController {
@Autowired
private UserService userService;
@Autowired
private LoginService loginService;
@GetMapping(value = "/")
public String index() {
return "success";
}
/**
* 本地登录
*/
@PostMapping(value = "/login")
public R login(@RequestBody @Valid LoginByAccountBO loginBO) {
AppUser user = loginService.localAuth(loginBO);
String token = userService.createToken(user);
Map<String, Object> rtnMap = new HashMap<>();
rtnMap.put("token", token);
rtnMap.put("user", user);
return R.ok().data(rtnMap);
}
@GetMapping(value = "/logout")
public R logout() {
//todo 拉黑token
return R.ok();
}
}
package cn.com.glsx.app.modules;
import cn.com.glsx.app.modules.entity.UserAuthRel;
import cn.com.glsx.app.modules.model.AppUser;
import cn.com.glsx.app.modules.model.QQLoginBO;
import cn.com.glsx.app.modules.model.WechatLoginBO;
import cn.com.glsx.app.modules.service.LoginService;
import cn.com.glsx.app.modules.service.UserService;
import cn.hutool.json.JSONUtil;
import com.glsx.plat.common.annotation.NoLogin;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* @author liuyf
* @Title UserController.java
* @Package com.hflw.vasp.controller
* @Description 微信登录
* @date 2019年10月24日 下午2:02:54
*/
@Slf4j
@RestController
public class ThirdLoginController {
private final WxMpService wxMpService;
@Resource
private UserService userService;
@Autowired
private LoginService loginService;
public ThirdLoginController(WxMpService wxMpService) {
this.wxMpService = wxMpService;
}
@NoLogin
@RequestMapping(value = "/wechatAuth")
public R wechatAuth(@RequestParam String code) throws WxErrorException {
WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
log.info("微信code[{}]获取的Token信息为{}", code, JSONUtil.toJsonStr(accessToken));
UserAuthRel authRel = loginService.wechatAuth(accessToken);
Map<String, Object> rtnMap = thirdLogin(authRel);
return R.ok().data(rtnMap);
}
@NoLogin
@PostMapping(value = "/wechatLogin")
public R wechatLogin(@RequestBody WechatLoginBO loginBO) {
log.info("微信授权参数 {}", loginBO.toString());
UserAuthRel wxAuthRel = loginService.wechatLogin(loginBO);
Map<String, Object> rtnMap = thirdLogin(wxAuthRel);
return R.ok().data(rtnMap);
}
@NoLogin
@RequestMapping(value = "/qqAuth")
public R qqAuth(@RequestParam String code) {
return R.ok();
}
@NoLogin
@RequestMapping(value = "/qqLogin")
public R qqLogin(@RequestBody QQLoginBO loginBO) {
log.info("QQ授权参数 {}", loginBO.toString());
UserAuthRel qqAuthRel = loginService.qqLogin(loginBO);
Map<String, Object> rtnMap = thirdLogin(qqAuthRel);
return R.ok().data(rtnMap);
}
private Map<String, Object> thirdLogin(UserAuthRel authRel) {
Map<String, Object> rtnMap = new HashMap<>();
Optional<Long> optUserId = Optional.ofNullable(authRel.getUserId());
if (optUserId.isPresent()) {
//如果用户id存在,理论上User不为空
AppUser user = userService.getAppUserByUserId(optUserId.get());
String token = userService.createToken(user);
rtnMap.put("token", token);
// rtnMap.put("user", UserConverter.INSTANCE.do2dto(user));
} else {
//没有绑定用户
rtnMap.put("authRelId", authRel.getId());
}
return rtnMap;
}
}
package cn.com.glsx.app.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_user_auth_rel")
public class UserAuthRel extends BaseEntity {
/**
* 用户id
*/
@Column(name = "user_id")
private Long userId;
/**
* 认证id
*/
@Column(name = "auth_id")
private Long authId;
/**
* 验证类型:local,third
*/
@Column(name = "auth_type")
private String authType;
}
\ No newline at end of file
package cn.com.glsx.app.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_user_local_account")
public class UserLocalAccount extends BaseEntity {
/**
* 用户id 为了方便,这里冗余用户id
*/
@Column(name = "user_id")
private Long userId;
/**
* 认证id
*/
@Column(name = "auth_id")
private Long authId;
/**
* 用户名/昵称
*/
private String username;
/**
* 头像
*/
private String avatar;
/**
* 平台id
*/
@Column(name = "union_id")
private String unionId;
}
\ No newline at end of file
package cn.com.glsx.app.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Table;
@Data
@Table(name = "t_user_local_auth")
public class UserLocalAuth extends BaseEntity {
/**
* 用户手机
*/
private String mobile;
/**
* 密码
*/
private String password;
}
\ No newline at end of file
package cn.com.glsx.app.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_user_qq_account")
public class UserQQAccount extends BaseEntity {
/**
* 认证id
*/
@Column(name = "auth_id")
private Long authId;
/**
* 平台id
*/
@Column(name = "union_id")
private String unionId;
/**
* QQ头像
*/
@Column(name = "qq_avatar")
private String avatar;
/**
* QQ名
*/
@Column(name = "qq_name")
private String qqName;
}
\ No newline at end of file
package cn.com.glsx.app.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_user_third_auth")
public class UserThirdAuth extends BaseEntity {
/**
* 第三方用户唯一标识
*/
private String openid;
/**
* 第三方平台标识(qq、wechat...)
*/
@Column(name = "login_type")
private String loginType;
/**
* 第三方获取的access_token,校验使用
*/
@Column(name = "access_token")
private String accessToken;
}
\ No newline at end of file
package cn.com.glsx.app.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_user_wechat_account")
public class UserWechatAccount extends BaseEntity {
/**
* 认证id
*/
@Column(name = "auth_id")
private Long authId;
/**
* 平台id
*/
@Column(name = "union_id")
private String unionId;
/**
* 微信头像
*/
@Column(name = "wechat_avatar")
private String avatar;
/**
* 微信名
*/
@Column(name = "wechat_name")
private String wechatName;
}
\ No newline at end of file
package cn.com.glsx.app.modules.mapper;
import cn.com.glsx.app.modules.entity.UserAuthRel;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserAuthRelMapper extends CommonBaseMapper<UserAuthRel> {
UserAuthRel selectById(@Param("id") Long id);
UserAuthRel selectLocalAuthRelByUserId(@Param("userId") Long userId);
UserAuthRel selectByAuthTypeAndAuthId(@Param("authType") String authType, @Param("authId") Long authId);
List<UserAuthRel> selectByAuthTypeAndUserId(@Param("authType") String authType, @Param("userId") Long userId);
List<UserAuthRel> selectByUserId(@Param("userId") Long userId);
int logicDeleteByUserId(@Param("userId") Long userId);
}
\ No newline at end of file
package cn.com.glsx.app.modules.mapper;
import cn.com.glsx.app.modules.entity.UserLocalAccount;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserLocalAccountMapper extends CommonBaseMapper<UserLocalAccount> {
UserLocalAccount selectByAuthId(@Param("authId") Long authId);
UserLocalAccount selectByUserId(@Param("userId") Long userId);
UserLocalAccount selectByUnionId(@Param("unionId") String unionId);
int logicDeleteById(@Param("id") Long id);
}
\ No newline at end of file
package cn.com.glsx.app.modules.mapper;
import cn.com.glsx.app.modules.entity.UserLocalAuth;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserLocalAuthMapper extends CommonBaseMapper<UserLocalAuth> {
UserLocalAuth selectById(@Param("id") Long id);
UserLocalAuth selectByUserId(@Param("userId") Long userId);
int updateMobileByUserId(@Param("userId") Long userId, @Param("mobile") String mobile);
int updatePasswordByUserId(@Param("userId") Long userId, @Param("password") String password);
int logicDeleteById(@Param("id") Long id);
}
\ No newline at end of file
package cn.com.glsx.app.modules.mapper;
import cn.com.glsx.app.modules.entity.UserQQAccount;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserQQAccountMapper extends CommonBaseMapper<UserQQAccount> {
UserQQAccount selectByAuthId(Long authId);
}
\ No newline at end of file
package cn.com.glsx.app.modules.mapper;
import cn.com.glsx.app.modules.entity.UserThirdAuth;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserThirdAuthMapper extends CommonBaseMapper<UserThirdAuth> {
UserThirdAuth selectByOpenid(@Param("openid") String openid);
UserThirdAuth selectByLoginTypeAndUserId(@Param("loginType") String loginType, @Param("userId") Long userId);
int logicDeleteById(@Param("id") Long id);
}
\ No newline at end of file
package cn.com.glsx.app.modules.mapper;
import cn.com.glsx.app.modules.entity.UserWechatAccount;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserWechatAccountMapper extends CommonBaseMapper<UserWechatAccount> {
UserWechatAccount selectByAuthId(Long authId);
}
\ No newline at end of file
package cn.com.glsx.app.modules.model;
import lombok.Data;
@Data
public class AppUser {
private Long id;
private String account;
private String username;
private String avatar;
private Integer gender;
private Integer blacklist;
}
package cn.com.glsx.app.modules.model;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
public class LoginByAccountBO {
/**
* 登录类型:1密码,2短信验证码
*/
@NotNull
private Integer loginType;
@NotBlank(message = "账号不能为空")
private String account;
@NotBlank(message = "验证码/密码不能为空")
private String code;
//@NotNull(message = "APP客户端ID不能为空")
private String clientId;
}
package cn.com.glsx.app.modules.model;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class QQLoginBO {
@NotBlank
private String openId;
}
package cn.com.glsx.app.modules.model;
import lombok.Data;
import java.io.Serializable;
@Data
public class QQOAuth2AccessToken implements Serializable {
private String accessToken;
private int expiresIn = -1;
private String refreshToken;
private String openId;
private String unionId;
}
package cn.com.glsx.app.modules.model;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class WechatLoginBO {
@NotBlank
private String openId;
@NotBlank
private String unionId;
}
package cn.com.glsx.app.modules.service;
import cn.com.glsx.app.common.enums.AuthType;
import cn.com.glsx.app.common.enums.LoginType;
import cn.com.glsx.app.common.exception.AppServerException;
import cn.com.glsx.app.modules.entity.*;
import cn.com.glsx.app.modules.mapper.*;
import cn.com.glsx.app.modules.model.*;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service
public class LoginService {
@Resource
private UserAuthRelMapper authRelMapper;
@Resource
private UserLocalAuthMapper localAuthMapper;
@Resource
private UserThirdAuthMapper thirdAuthMapper;
@Resource
private UserLocalAccountMapper localAccountMapper;
@Resource
private UserWechatAccountMapper wechatAccountMapper;
@Resource
private UserQQAccountMapper qqAccountMapper;
@Transactional(rollbackFor = Exception.class)
public AppUser localAuth(LoginByAccountBO loginBO) {
// TODO: 2022/3/24 内部登录转成appUser返回前端
AppUser appUser = new AppUser();
UserAuthRel userAuthRel = authRelMapper.selectLocalAuthRelByUserId(appUser.getId());
if (loginBO.getLoginType() == 1) {
//密码登录
UserLocalAuth localAuth = localAuthMapper.selectById(userAuthRel.getAuthId());
if (localAuth == null) {
throw new AppServerException("请先开通登录权限");
}
} else if (loginBO.getLoginType() == 2) {
//验证码校验
//smsService.verifyCode(loginBO.getAccount(), loginBO.getCode());
}
return appUser;
}
@Transactional(rollbackFor = Exception.class)
public UserAuthRel qqAuth(QQOAuth2AccessToken accessToken) {
UserThirdAuth thirdAuth = thirdAuthMapper.selectByOpenid(accessToken.getOpenId());
if (thirdAuth == null) {
thirdAuth = new UserThirdAuth();
thirdAuth.setOpenid(accessToken.getOpenId());
thirdAuth.setAccessToken(accessToken.getAccessToken());
thirdAuth.setLoginType(LoginType.QQ.getType());
thirdAuthMapper.insertUseGeneratedKeys(thirdAuth);
}
UserQQAccount qqAccount = qqAccountMapper.selectByAuthId(thirdAuth.getId());
if (qqAccount == null) {
qqAccount = new UserQQAccount();
qqAccount.setAuthId(thirdAuth.getId());
qqAccount.setUnionId(accessToken.getUnionId());
qqAccountMapper.insertUseGeneratedKeys(qqAccount);
}
UserAuthRel authRel = authRelMapper.selectByAuthTypeAndAuthId(AuthType.THIRD.getType(), thirdAuth.getId());
if (authRel == null) {
authRel = new UserAuthRel();
authRel.setAuthId(thirdAuth.getId());
authRel.setAuthType(AuthType.THIRD.getType());
authRelMapper.insertUseGeneratedKeys(authRel);
}
return authRel;
}
@Transactional(rollbackFor = Exception.class)
public UserAuthRel qqLogin(QQLoginBO loginBO) {
UserThirdAuth thirdAuth = thirdAuthMapper.selectByOpenid(loginBO.getOpenId());
if (thirdAuth == null) {
thirdAuth = new UserThirdAuth();
thirdAuth.setOpenid(loginBO.getOpenId());
thirdAuth.setLoginType(LoginType.QQ.getType());
thirdAuthMapper.insertUseGeneratedKeys(thirdAuth);
}
UserQQAccount qqAccount = qqAccountMapper.selectByAuthId(thirdAuth.getId());
if (qqAccount == null) {
qqAccount = new UserQQAccount();
qqAccount.setAuthId(thirdAuth.getId());
qqAccountMapper.insertUseGeneratedKeys(qqAccount);
}
UserAuthRel authRel = authRelMapper.selectByAuthTypeAndAuthId(AuthType.THIRD.getType(), thirdAuth.getId());
if (authRel == null) {
authRel = new UserAuthRel();
authRel.setAuthId(thirdAuth.getId());
authRel.setAuthType(AuthType.THIRD.getType());
authRelMapper.insertUseGeneratedKeys(authRel);
}
return authRel;
}
@Transactional(rollbackFor = Exception.class)
public UserAuthRel wechatAuth(WxOAuth2AccessToken accessToken) {
UserThirdAuth thirdAuth = thirdAuthMapper.selectByOpenid(accessToken.getOpenId());
if (thirdAuth == null) {
thirdAuth = new UserThirdAuth();
thirdAuth.setOpenid(accessToken.getOpenId());
thirdAuth.setAccessToken(accessToken.getAccessToken());
thirdAuth.setLoginType(LoginType.WECHAT.getType());
thirdAuthMapper.insertUseGeneratedKeys(thirdAuth);
}
UserWechatAccount wechatAccount = wechatAccountMapper.selectByAuthId(thirdAuth.getId());
if (wechatAccount == null) {
wechatAccount = new UserWechatAccount();
wechatAccount.setAuthId(thirdAuth.getId());
wechatAccount.setUnionId(accessToken.getUnionId());
wechatAccountMapper.insertUseGeneratedKeys(wechatAccount);
}
UserAuthRel authRel = authRelMapper.selectByAuthTypeAndAuthId(AuthType.THIRD.getType(), thirdAuth.getId());
if (authRel == null) {
authRel = new UserAuthRel();
authRel.setAuthId(thirdAuth.getId());
authRel.setAuthType(AuthType.THIRD.getType());
authRelMapper.insertUseGeneratedKeys(authRel);
}
return authRel;
}
@Transactional(rollbackFor = Exception.class)
public UserAuthRel wechatLogin(WechatLoginBO loginBO) {
UserThirdAuth thirdAuth = thirdAuthMapper.selectByOpenid(loginBO.getOpenId());
if (thirdAuth == null) {
thirdAuth = new UserThirdAuth();
thirdAuth.setOpenid(loginBO.getOpenId());
thirdAuth.setLoginType(LoginType.WECHAT.getType());
thirdAuthMapper.insertUseGeneratedKeys(thirdAuth);
}
UserWechatAccount wechatAccount = wechatAccountMapper.selectByAuthId(thirdAuth.getId());
if (wechatAccount == null) {
wechatAccount = new UserWechatAccount();
wechatAccount.setAuthId(thirdAuth.getId());
wechatAccount.setUnionId(loginBO.getUnionId());
wechatAccountMapper.insertUseGeneratedKeys(wechatAccount);
}
UserAuthRel authRel = authRelMapper.selectByAuthTypeAndAuthId(AuthType.THIRD.getType(), thirdAuth.getId());
if (authRel == null) {
authRel = new UserAuthRel();
authRel.setAuthId(thirdAuth.getId());
authRel.setAuthType(AuthType.THIRD.getType());
authRelMapper.insertUseGeneratedKeys(authRel);
}
return authRel;
}
}
package cn.com.glsx.app.modules.service;
import cn.com.glsx.app.modules.model.AppUser;
import cn.hutool.core.lang.UUID;
import com.glsx.plat.common.utils.ObjectUtils;
import com.glsx.plat.jwt.base.ComJwtUser;
import com.glsx.plat.jwt.util.JwtUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.Map;
@Service
public class UserService {
@Resource
private JwtUtils<ComJwtUser> jwtUtils;
/**
* 生成带用户信息的token
*
* @param user
* @return
*/
public String createToken(AppUser user) {
Assert.notNull(user, "获取当前用户信息失败");
String uuid = UUID.randomUUID().toString(); //JWT 随机ID,做为验证的key
String jwtId = jwtUtils.getApplication() + ":" + uuid + "_" + jwtUtils.JWT_SESSION_PREFIX + user.getId();
ComJwtUser jwtUser = new ComJwtUser();
jwtUser.setApplication(jwtUtils.getApplication());
jwtUser.setJwtId(jwtId);
jwtUser.setUserId(String.valueOf(user.getId()));
jwtUser.setAccount(user.getAccount());
Map<String, Object> userMap = (Map<String, Object>) ObjectUtils.objectToMap(jwtUser);
return jwtUtils.createToken(userMap);
}
public AppUser getAppUserByUserId(Long aLong) {
return null;
}
}
#项目名称
spring.application.name=glsx-rest-appserver
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.3.206:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=DEV_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
#spring.profiles.active=DEV
#配置格式
#spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-rest-admin-share.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.app.modules.mapper.UserAuthRelMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.app.modules.entity.UserAuthRel">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="user_id" jdbcType="INTEGER" property="userId"/>
<result column="auth_id" jdbcType="INTEGER" property="authId"/>
<result column="auth_type" jdbcType="VARCHAR" property="authType"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, user_id, auth_id, auth_type, del_flag, created_date, created_by, updated_date,
updated_by
</sql>
<select id="selectByAuthTypeAndAuthId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_auth_rel
where auth_type = #{authType}
and auth_id = #{authId}
and del_flag = 0
</select>
<select id="selectByAuthTypeAndUserId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_auth_rel
where auth_type = #{authType}
and user_id = #{userId}
and del_flag = 0
</select>
<select id="selectLocalAuthRelByUserId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_auth_rel
where auth_type = 'local'
and user_id = #{userId}
and del_flag = 0
limit 1
</select>
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_auth_rel
where id = #{id}
and del_flag = 0
</select>
<select id="selectByUserId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_auth_rel
where user_id = #{userId}
and del_flag = 0
</select>
<update id="logicDeleteByUserId">
update t_user_auth_rel
set del_flag = -1
where user_id = #{userId}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.app.modules.mapper.UserLocalAccountMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.app.modules.entity.UserLocalAccount">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="user_id" jdbcType="INTEGER" property="userId"/>
<result column="auth_id" jdbcType="INTEGER" property="authId"/>
<result column="union_id" jdbcType="VARCHAR" property="unionId"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="avatar" jdbcType="VARCHAR" property="avatar"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, user_id, auth_id, union_id, username, avatar, del_flag, created_date, created_by,
updated_date, updated_by
</sql>
<select id="selectByAuthId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_local_account
where auth_id = #{authId}
and del_flag = 0
</select>
<select id="selectByUserId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_local_account
where user_id = #{userId}
and del_flag = 0
</select>
<select id="selectByUnionId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_local_account
where union_id = #{unionId}
and del_flag = 0
</select>
<update id="logicDeleteById">
update t_user_local_account
set del_flag = -1
where id = #{id}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.app.modules.mapper.UserLocalAuthMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.app.modules.entity.UserLocalAuth">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="mobile" jdbcType="VARCHAR" property="mobile"/>
<result column="password" jdbcType="VARCHAR" property="password"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, mobile, `password`, del_flag, created_date, created_by,
updated_date, updated_by
</sql>
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_local_auth
where id = #{id}
and del_flag = 0
</select>
<select id="selectByUserId" resultMap="BaseResultMap">
select tcula.id, tcula.mobile, tcula.`password`, tcuar.user_id, tcuar.auth_id
from t_user_local_auth tcula,
t_user_auth_rel tcuar
where tcula.id = tcuar.auth_id
and auth_type = 'local'
and tcuar.user_id = #{userId}
and tcuar.del_flag = 0 limit 1
</select>
<update id="updateMobileByUserId">
update t_user_local_auth tcula ,t_user_auth_rel tcuar,t_user tcu
set tcula.mobile = #{mobile},
tcu.account = #{mobile}
where tcula.id = tcuar.auth_id
and auth_type = 'local'
and tcuar.user_id = tcu.id
and tcuar.user_id = #{userId}
</update>
<update id="updatePasswordByUserId">
update t_user_local_auth tcula ,t_user_auth_rel tcuar
set tcula.password = #{password}
where tcula.id = tcuar.auth_id
and auth_type = 'local'
and tcuar.user_id = #{userId}
</update>
<update id="logicDeleteById">
update t_user_local_auth
set del_flag = -1
where id = #{id}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.app.modules.mapper.UserQQAccountMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.app.modules.entity.UserQQAccount">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="auth_id" jdbcType="INTEGER" property="authId"/>
<result column="union_id" jdbcType="VARCHAR" property="unionId"/>
<result column="qq_avatar" jdbcType="VARCHAR" property="qqAvatar"/>
<result column="qq_name" jdbcType="VARCHAR" property="qqName"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, auth_id, union_id, qq_avatar, qq_name, del_flag, created_date, created_by, updated_date,
updated_by
</sql>
<select id="selectByAuthId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_qq_account
where auth_id = #{authId}
and del_flag = 0
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.app.modules.mapper.UserThirdAuthMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.app.modules.entity.UserThirdAuth">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="openid" jdbcType="VARCHAR" property="openid"/>
<result column="login_type" jdbcType="VARCHAR" property="loginType"/>
<result column="access_token" jdbcType="VARCHAR" property="accessToken"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, openid, login_type, access_token, del_flag, created_date, created_by, updated_date,
updated_by
</sql>
<select id="selectByOpenid" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_third_auth
where openid = #{openid}
and del_flag = 0
</select>
<select id="selectByLoginTypeAndUserId" resultMap="BaseResultMap">
select tcuta.*
from t_user_third_auth tcuta,
t_user_auth_rel tcuar
where tcuta.id = tcuar.auth_id
and tcuar.auth_type = 'third'
and tcuta.login_type = #{loginType}
and tcuar.user_id = #{userId}
and tcuta.del_flag = 0
and tcuar.del_flag = 0
</select>
<update id="logicDeleteById">
update t_user_third_auth
set del_flag = -1
where id = #{id}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.app.modules.mapper.UserWechatAccountMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.app.modules.entity.UserWechatAccount">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="auth_id" jdbcType="INTEGER" property="authId"/>
<result column="union_id" jdbcType="VARCHAR" property="unionId"/>
<result column="wechat_avatar" jdbcType="VARCHAR" property="wechatAvatar"/>
<result column="wechat_name" jdbcType="VARCHAR" property="wechatName"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, auth_id, union_id, wechat_avatar, wechat_name, del_flag, created_date, created_by,
updated_date, updated_by
</sql>
<select id="selectByAuthId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user_wechat_account
where auth_id = #{authId}
and del_flag = 0
</select>
</mapper>
\ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8820"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="glsx-rest-admin"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="glsx-rest-admin"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file
package cn.com.glsx.app;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!