Commit cc68d0ce by 111-PC\111

[+]代码提交

0 parents
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>smartDevices-platform-service</artifactId>
<properties>
<kaptcha.version>0.0.9</kaptcha.version>
<shiro.version>1.6.0</shiro.version>
</properties>
<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-common</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-redis</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<!--mybatis 逆向生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<!-- <phase>package</phase>-->
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>false</overwrite>
<!-- 自动生成的配置 -->
<configurationFile>src/main/resources/config/generatorConfig.xml</configurationFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
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
@EnableDiscoveryClient
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication(scanBasePackages = {"cn.com.glsx"})
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.common;
/**
* @author zhouhaibao
* @date 2021/3/4 9:53
*/
public class Constants {
// 涂鸦立牌rediskey
public static final String ACCESSTOKEN_REDISKEY="accessToken_redisKey";
}
package cn.com.glsx.common.redis;
import cn.com.glsx.modules.model.param.AccessToken;
import org.springframework.stereotype.Component;
@Component
public class AccessTokenRedis extends RedisService {
public AccessToken readCache(String key){
Object alarmObject = redisTemplate.opsForValue().get(key);
return (AccessToken) alarmObject;
}
public void add(String key,AccessToken value){
redisTemplate.opsForValue().set(key,value);
}
}
package cn.com.glsx.common.redis;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* redis 操作工具类
*/
@Component
public class RedisService {
@Resource(name = "redisTemplate")
protected RedisTemplate<Object,Object> redisTemplate;
protected Log logger = LogFactory.getLog(getClass());
public void set(String key, Object value) {
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public void setList(String key, List<?> value) {
ListOperations listOperations = redisTemplate.opsForList();
listOperations.leftPush(key, value);
}
public Object getList(String key) {
return redisTemplate.opsForList().leftPop(key);
}
public void setSet(String key, Set<?> value) {
SetOperations setOperations = redisTemplate.opsForSet();
setOperations.add(key, value);
}
public Object getSet(String key) {
return redisTemplate.opsForSet().members(key);
}
public void setHash(String key, Map<String, ?> value) {
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.putAll(key, value);
}
public Object getHash(String key) {
return redisTemplate.opsForHash().entries(key);
}
public void delete(String key) {
redisTemplate.delete(key);
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.modules.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author zhouhaibao
* @date 2021/3/4 17:05
*/
@Controller
@RequestMapping("/device")
public class DeviceController {
}
package cn.com.glsx.modules.controller;
import cn.com.glsx.modules.model.param.UserBo;
import cn.com.glsx.modules.model.param.UserInfo;
import cn.com.glsx.modules.service.UserService;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.core.web.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 对接涂鸦用户模块
*
* @author zhouhaibao
* @date 2021/3/3 17:35
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 注册用户信息
*
* @param userBo 用户信息
* @return
*/
@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
@ResponseBody
public R registerUser(@RequestBody UserBo userBo) {
String uid = userService.registerUser(userBo);
if(StringUtils.isNotBlank(uid)){
return R.ok(uid);
}
return R.error();
}
/**
* 根据id查询用户信息
*
* @param id 用户id
* @return 用户信息
*/
@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
@ResponseBody
public R getUserInfo(@PathVariable String id) {
UserInfo userInfo = userService.getUserInfo(id);
return R.ok(JSONObject.toJSONString(userInfo));
}
}
package cn.com.glsx.modules.model.param;
import lombok.Data;
import java.util.List;
/**
* @author zhouhaibao
* @date 2021/3/4 10:10
*/
@Data
public class AccessToken {
private String access_token;
private Long expire_time;
private String refresh_token;
private String uid;
}
package cn.com.glsx.modules.model.param;
import lombok.Data;
/**
* @author zhouhaibao
* @date 2021/3/4 10:30
*/
@Data
public class ResponseBody {
/**
* 返回的结果
*/
private boolean success;
/**
* 返回的数据
*/
private String result;
}
package cn.com.glsx.modules.model.param;
import lombok.Data;
/**
* @author zhouhaibao
* @date 2021/3/3 17:33
*/
@Data
public class UserBo {
private String username;
private String password;
private String username_type;
private String country_code;
}
package cn.com.glsx.modules.model.param;
import lombok.Data;
/**
* @author zhouhaibao
* @date 2021/3/4 11:07
*/
@Data
public class UserInfo {
private String avatar;
private String country_code;
private Long create_time;
private String email;
private String mobile;
private String nick_name;
private String uid;
private String time_zone_id;
private String username;
private Integer temp_unit;
private Long update_time;
}
package cn.com.glsx.modules.service;
import cn.com.glsx.common.Constants;
import cn.com.glsx.common.redis.AccessTokenRedis;
import cn.com.glsx.modules.model.param.AccessToken;
import cn.com.glsx.modules.model.param.ResponseBody;
import cn.com.glsx.modules.model.param.UserBo;
import cn.com.glsx.modules.model.param.UserInfo;
import cn.com.glsx.modules.utils.AccessTokenService;
import cn.com.glsx.modules.utils.HttpUtil;
import cn.com.glsx.modules.utils.TuyaUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author zhouhaibao
* @date 2021/3/3 17:23
*/
@Service
@Slf4j
public class UserService {
@Value("${tuya.registerUserUrl}")
private String registerUserUrl;
@Value("${tuya.getUserInfoUrl}")
private String getUserInfoUrl;
@Value("${tuya.sign_method}")
private String sign_method;
@Value("${tuya.client_id}")
private String client_id;
@Value("${tuya.secret}")
private String secret;
@Autowired
private AccessTokenService accessTokenService;
/**
* 注册用户
*
* @param userBo 用户
*/
public String registerUser(UserBo userBo) {
//获取令牌
String uid=null;
String accessToken = accessTokenService.getAccessToken();
if (StringUtils.isNotBlank(accessToken)) {
ResponseBody responseBody = sendRequestRegisterUser(accessToken, userBo);
if(responseBody!=null&&responseBody.isSuccess()){
String result = responseBody.getResult();
JSONObject jsonObject = JSONObject.parseObject(result);
uid = jsonObject.getString("uid");
}else{
log.info("调用涂鸦失败");
}
} else {
log.info("调用涂鸦鉴权失败");
}
return uid;
}
private ResponseBody sendRequestRegisterUser(String accessToken, UserBo userBo) {
ResponseBody responseBody = null;
long timeMillis = System.currentTimeMillis();
String sign = TuyaUtils.getBussinessSign(timeMillis, client_id, secret, accessToken);
Map<String, String> headerParams = new HashMap<>();
headerParams.put("client_id", client_id);
headerParams.put("t", timeMillis + "");
headerParams.put("sign_method", "HMAC-SHA256");
headerParams.put("sign", sign);
headerParams.put("access_token", accessToken);
try {
JSONObject jsonObject = HttpUtil.sendPost(registerUserUrl, JSONObject.toJSONString(userBo), headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("调用涂鸦注册用户失败");
}
return responseBody;
}
/**
* 获取用户信息
*
* @param id 用户 ID
*/
public UserInfo getUserInfo(String id) {
UserInfo userInfo = null;
String accessToken = accessTokenService.getAccessToken();
if (StringUtils.isNotBlank(accessToken)) {
ResponseBody responseBody = sendRequestGetUserInfo(id, accessToken);
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
userInfo = JSONObject.parseObject(result, UserInfo.class);
} else {
log.info("调用涂鸦用户信息接口失败");
}
} else {
log.info("调用涂鸦鉴权失败");
}
return userInfo;
}
private ResponseBody sendRequestGetUserInfo(String id, String accessToken) {
ResponseBody responseBody = null;
long timeMillis = System.currentTimeMillis();
String sign = TuyaUtils.getBussinessSign(timeMillis, client_id, secret, accessToken);
Map<String, String> headerParams = new HashMap<>();
headerParams.put("client_id", client_id);
headerParams.put("t", timeMillis + "");
headerParams.put("sign_method", "HMAC-SHA256");
headerParams.put("sign", sign);
headerParams.put("access_token", accessToken);
try {
JSONObject jsonObject = HttpUtil.sendGet(getUserInfoUrl.replace("{uid}", id), null, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求用户信息接口异常,异常信息{}", e);
}
return responseBody;
}
}
package cn.com.glsx.modules.utils;
import cn.com.glsx.common.Constants;
import cn.com.glsx.common.redis.AccessTokenRedis;
import cn.com.glsx.modules.model.param.AccessToken;
import cn.com.glsx.modules.model.param.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* 获取涂鸦令牌
*
* @author zhouhaibao
* @date 2021/3/4 14:39
*/
@Service
@Slf4j
public class AccessTokenService {
@Autowired
private AccessTokenRedis accessTokenRedis;
@Value("${tuya.tokenFlashUrl}")
private String tokenFlashUrl;
@Value("${tuya.sign_method}")
private String sign_method;
@Value("${tuya.client_id}")
private String client_id;
@Value("${tuya.secret}")
private String secret;
@Value("${tuya.getTokenUrl}")
private String getTokenUrl;
@Value("${tuya.registerUserUrl}")
private String registerUserUrl;
/**
* 获取涂鸦令牌
*
* @return
*/
public String getAccessToken() {
String access_Token = null;
AccessToken accessToken = accessTokenRedis.readCache(Constants.ACCESSTOKEN_REDISKEY);
if (null != accessToken) {
if ((accessToken.getExpire_time() - System.currentTimeMillis()) >= 1000 * 60 * 60 * 2) {
ResponseBody responseBody = sendRequestFlashToken(accessToken.getRefresh_token());
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
AccessToken token = JSONObject.parseObject(result, AccessToken.class);
token.setExpire_time(System.currentTimeMillis());
accessTokenRedis.add(Constants.ACCESSTOKEN_REDISKEY, token);
access_Token = token.getAccess_token();
} else {
log.info("调用刷新令牌接口异常");
}
} else {
access_Token = accessToken.getAccess_token();
}
} else {
ResponseBody responseBody = sendRequestGetToken();
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
AccessToken token = JSONObject.parseObject(result, AccessToken.class);
token.setExpire_time(System.currentTimeMillis());
accessTokenRedis.add(Constants.ACCESSTOKEN_REDISKEY, token);
access_Token = token.getAccess_token();
} else {
log.info("调用获取accesstoken接口异常");
}
}
return access_Token;
}
/**
* 发送刷新令牌请求
*
* @return
*/
private ResponseBody sendRequestFlashToken(String flashtoken) {
ResponseBody responseBody = null;
long timeMillis = System.currentTimeMillis();
String sign = TuyaUtils.getLoginSign(timeMillis, client_id, secret);
Map<String, String> headerParams = new HashMap<>();
headerParams.put("client_id", client_id);
headerParams.put("t", timeMillis + "");
headerParams.put("sign_method", "HMAC-SHA256");
headerParams.put("sign", sign);
try {
JSONObject jsonObject = HttpUtil.sendGet(tokenFlashUrl + flashtoken, null, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求刷新token接口异常,异常信息{}", e);
}
return responseBody;
}
/**
* 发送请求获取涂鸦token
*
* @return
*/
private ResponseBody sendRequestGetToken() {
ResponseBody responseBody = null;
long timeMillis = System.currentTimeMillis();
String loginSign = TuyaUtils.getLoginSign(timeMillis, client_id, secret);
Map<String, String> headerParams = new HashMap<>();
headerParams.put("client_id", client_id);
headerParams.put("t", timeMillis + "");
headerParams.put("sign_method", "HMAC-SHA256");
headerParams.put("sign", loginSign);
try {
JSONObject jsonObject = HttpUtil.sendGet(getTokenUrl, null, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求获取token接口异常,异常信息{}", e);
}
return responseBody;
}
}
package cn.com.glsx.modules.utils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
/**
* 获取涂鸦签名
*
* @author zhouhaibao
* @date 2021/3/3 14:23
*/
public class TuyaUtils {
/**
* 获取令牌签名
*
* @param time 时间戳
* @param client_id client_id
* @param secret secret
* @return
*/
public static String getLoginSign(long time, String client_id, String secret) {
String hash=null;
try {
String message = client_id + time;
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
hash = new HexBinaryAdapter().marshal(bytes).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
}
return hash;
}
/**
* 获取业务的签名
*
* @param time 时间戳
* @param client_id client_id
* @param secret secret
* @param accessToken 令牌
* @return
*/
public static String getBussinessSign(long time, String client_id, String secret, String accessToken) {
String hash=null;
try {
String message = client_id + accessToken + time;
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
hash = new HexBinaryAdapter().marshal(bytes).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
}
return hash;
}
}
#项目名称
spring.application.name=glsx-tuya
#日志路径(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.0.63: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=NESHIELD_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=NESHIELD_DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-ne-shield-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
#sentinel数据源配置
spring.cloud.sentinel.datasource.ds2.nacos.server-addr=${spring.cloud.nacos.config.server-addr}
spring.cloud.sentinel.datasource.ds2.nacos.username=nacos
spring.cloud.sentinel.datasource.ds2.nacos.password=nacos
spring.cloud.sentinel.datasource.ds2.nacos.data-id=glsx-ne-shield-sentinel-dev.json
spring.cloud.sentinel.datasource.ds2.nacos.group-id=NESHIELD_DEV_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=flow
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!-- <classPathEntry location="F://jdbc//mysql-connector-java-8.0.18.jar"/>-->
<!-- 一个数据库一个context -->
<context id="DB2Tables" targetRuntime="Mybatis3">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true"/>
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 配置 tk.mybatis 插件 -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.glsx.plat.mybatis.mapper.CommonBaseMapper"/>
</plugin>
<!--配置生成注释信息,最多配置一个 -->
<commentGenerator>
<!-- 阻止生成注释包含时间戳 默认为false -->
<property name="suppressDate" value="true"/>
<!-- 注释是否添加数据库表的备注信息 默认为false -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- jdbc连接-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.0.39:3306/neshield?serverTimeZone=Shanghai&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
userId="root"
password="123456">
<!--防止生成其他库同名表-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.glsx.neshield.modules.entity" targetProject="src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值去掉前后空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapper.xml文件存放地址 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成接口dao type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.glsx.neshield.modules.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
<table tableName="t_user_path" domainObjectName="UserPath" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
\ No newline at end of file \ 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 \ 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 \ 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="8883"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="glsx-ne-shield-usercenter"
###########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 \ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="glsx-ne-shield-usercenter"
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 \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!