【项目实践】_公共模块的抽取


1.1 公共模块

导入maven依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
<parent>
<groupId>com.truly</groupId>
<artifactId>truly_shopp_parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>truly_shopping_common</artifactId>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>

base类封装

  • 响应类ResponseBase
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.truly.base;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ResponseBase {
// 响应code
private Integer code;
// 消息内容
private String msg;
// 返回data
private Object data;

public ResponseBase() {
}

public ResponseBase(Integer code, String msg, Object data) {
super();
this.code = code;
this.msg = msg;
this.data = data;
}
}
  • BaseRedisService操作类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.truly.base;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class BaseRedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;

public void setString(String key, String data, Long timeout) {
this.setObject(key, data, timeout);
}

public Object getString(String key) {
return stringRedisTemplate.opsForValue().get(key);
}

public void delKey(String key) {
stringRedisTemplate.delete(key);
}

private void setObject(String key, Object data, Long timeout) {
if (StringUtils.isEmpty(key) || data == null)
return;
if (data instanceof String) {
String value = (String) data;
stringRedisTemplate.opsForValue().set(key, value);
if (timeout != null) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
return;
}
if (data instanceof List) {
List<String> value = (List<String>) data;
for (String oneValue : value) {
stringRedisTemplate.opsForList().leftPush(key, oneValue);
}
if (timeout != null) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
return;
}
}

private Object getObject(String key) {
if (StringUtils.isEmpty(key))
return null;
return null;
}
}
  • BaseService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.truly.base;

import com.qiu.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BaseApiService {
@Autowired
protected BaseRedisService baseRedisService;
//返回失败
public ResponseBase setResultError(String msg){
return setResult(Constants.HTTP_RES_CODE_500,msg,null);
};
//返回自定义失败码及消息
public ResponseBase setResultError(Integer code,String msg){
return setResult(code,msg,null);
};
//返回成功传data值
public ResponseBase setResultSuccess(Object data){
return setResult(Constants.HTTP_RES_CODE_200,Constants.HTTP_RES_CODE_200_VALUE,data);
};
//返回成功传消息
public ResponseBase setResultSuccess(String msg){
return setResult(Constants.HTTP_RES_CODE_200,msg,null);
};
//返回成功但没data值
public ResponseBase setResultSuccess(){
return setResult(Constants.HTTP_RES_CODE_200,Constants.HTTP_RES_CODE_200_VALUE,null);
};
//通用封装
private ResponseBase setResult(Integer code,String msg,Object data){
return new ResponseBase(code,msg,data);
};
}
  • 微信消息工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.qiu.base;

import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Setter
@Getter
public class BaseMessage {
/**
* 开发者微信
*/
private String ToUserName;
/**
* 发送openid
*/
private String FromUserName;
/**
* 创建时间
*/
private Long CreateTime;
/**
* 内容类型
*/
private String MsgType;

}
  • 继承消息类
1
2
3
4
5
6
7
8
9
10
package com.truly.base;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class TextMassage extends BaseMessage {
private String Content;
}
  • 打印日志
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.truly.base;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.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.Enumeration;

@Aspect
@Component
@Slf4j
public class LogAspectServiceApi {

private JSONObject jsonObject= new JSONObject();
//声明一个切点,里面为切点表达式
@Pointcut("execution(public * com.qiu.api.service.*.*(..))")
public void controllerAspect(){

}
//请求method打印内容
@Before(value = "controllerAspect()")
public void methodBefore(JoinPoint joinPoint){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//记录下请求内容
log.info("###########请求开始##################");
try {
log.info("URL:" + request.getRequestURI().toString());
log.info("Http_METHOD:" + request.getMethod());
log.info("IP:" + request.getRemoteAddr());
}catch (Exception e){
log.error("##########LogAspectServiceApi.class methodBefore() ###### ERROR",e);
}
Enumeration<String> enu = request.getParameterNames();
while (enu.hasMoreElements()){
String name = enu.nextElement();
log.info("name:{"+name+"},value:{"+request.getParameter(name)+"}");
}
log.info("###########请求结束##################");
}
@AfterReturning(returning = "res",pointcut = "controllerAspect()")
public void doAfterReturning(Object res){
//处理完请求,返回内容
log.info("------------------返回内容--------------");
try{
log.info("Response内容:"+jsonObject.toJSONString(res));
}catch (Exception e){
log.error("#####LogServiceApi.class methodAfterReturning() ### ERROR",e);
}
log.info("------------------返回内容--------------");
}
}

工具类封装

  • ListUtils封装
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ListUtils {

//判断list集合是否为空
public List<?> emptyList(List<?> list) {
if (list == null || list.size() <= 0) {
return null;
}
return list;
}
//判断map集合是否为空
public Map<?,?> emptyMap(Map<?,?> map) {
if (map == null || map.size() <= 0) {
return null;
}
return map;
}
}
  • cookie工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.truly.utils;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* cookie工具类 获取 设置cookie
* @author sanch
*
*/
public class CookieUtil {

/**
* 添加cookie
* @param res 返回cookie response对象
* @param name Cookie的key
* @param value Cookie的value
* @param maxAge Cookie的有效时长 默认-1
*/
public static void addCookie(HttpServletResponse res,String name,String value,int maxAge){
Cookie cookie = new Cookie(name,value);
if(maxAge > 0){
cookie.setMaxAge(maxAge);
}
res.addCookie(cookie);
}

/**
* 根据cookie的key 获取Cookie对象
* @param req
* @param name
* @return
*/
public static Cookie getCookieByName(HttpServletRequest req,String name){
Cookie cookie = null;
Map<String, Cookie> cookieMap = ReadCookieMap(req);
if(cookieMap.containsKey(name)){
return cookieMap.get(name);
}

return null;
}

/**
* 读取Cookie
* @param req
* @return 返回cookie的map集合
*/
public static Map<String, Cookie> ReadCookieMap(HttpServletRequest req){
Map<String, Cookie> map = new HashMap<String, Cookie>();
Cookie[] cookies = req.getCookies();
for(Cookie cookie : cookies){
map.put(cookie.getName(), cookie);
}
return map;
}

/**
* 清除cookie
* @param response
* @param killcookie
*/
public static void killCookie(HttpServletResponse response,Cookie killcookie){
killcookie.setValue(null);
killcookie.setMaxAge(0);
killcookie.setPath("/");
response.addCookie(killcookie);
}
}
  • MD5工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package com.truly.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* @ClassName MD5Util
* @Description MD5工具类
* @Author
* @Date 2021/6/23 11:47 下午
* @Version 1.0
*/
public class MD5Util {


static final char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
static final char hexDigitsLower[] = { '0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

/**
* @Description //对字符串 MD5 无盐值加密
* @author dsp
* @date 2021/6/23
* @param plainText 传入要加密的字符串
* @return java.lang.String MD5加密后生成32位(小写字母+数字)字符串
*/
public static String MD5Lower(String plainText) {
try {
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest md = MessageDigest.getInstance("MD5");

// 使用指定的字节更新摘要
md.update(plainText.getBytes());

// digest()最后确定返回md5 hash值,返回值为8位字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值。1 固定值
return new BigInteger(1, md.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}


/**
* @Description // 对字符串 MD5 加密
* @author dsp
* @date 2021/6/23
* @param plainText 传入要加密的字符串
* @return java.lang.String MD5加密后生成32位(大写字母+数字)字符串
*/
public static String MD5Upper(String plainText) {
try {
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest md = MessageDigest.getInstance("MD5");

// 使用指定的字节更新摘要
md.update(plainText.getBytes());

// 获得密文
byte[] mdResult = md.digest();
// 把密文转换成十六进制的字符串形式
int j = mdResult.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = mdResult[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* @Description //对字符串 MD5 加盐值加密
* @author dsp
* @date 2021/6/23
* @param plainText 传入要加密的字符串
* @param saltValue 传入要加的盐值
* @return java.lang.String MD5加密后生成32位(小写字母+数字)字符串
*/
public static String MD5Lower(String plainText, String saltValue) {
try {
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest md = MessageDigest.getInstance("MD5");

// 使用指定的字节更新摘要
md.update(plainText.getBytes());
md.update(saltValue.getBytes());

// digest()最后确定返回md5 hash值,返回值为8位字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值。1 固定值
return new BigInteger(1, md.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}

/**
* @Description //对字符串 MD5 加盐值加密
* @author dsp
* @date 2021/6/23
* @param plainText 传入要加密的字符串
* @param saltValue 传入要加的盐值
* @return java.lang.String MD5加密后生成32位(大写字母+数字)字符串
*/
public static String MD5Upper(String plainText, String saltValue) {
try {
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest md = MessageDigest.getInstance("MD5");

// 使用指定的字节更新摘要
md.update(plainText.getBytes());
md.update(saltValue.getBytes());

// 获得密文
byte[] mdResult = md.digest();
// 把密文转换成十六进制的字符串形式
int j = mdResult.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = mdResult[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* @Description //MD5加密后生成32位(小写字母+数字)字符串,同 MD5Lower() 一样
* @author dsp
* @date 2021/6/23
* @param plainText
* @return java.lang.String
*/
public final static String MD5(String plainText) {
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");

mdTemp.update(plainText.getBytes("UTF-8"));

byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigitsLower[byte0 >>> 4 & 0xf];
str[k++] = hexDigitsLower[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}

/**
* @Description //校验MD5码
* @author dsp
* @date 2021/6/23
* @param text 要校验的字符串
* @param md5 md5值
* @return boolean 校验结果
*/
public static boolean valid(String text, String md5) {
return md5.equals(MD5(text)) || md5.equals(MD5(text).toUpperCase());
}

}
  • Token工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.truly.utils;

import com.qiu.constants.Constants;

import java.util.UUID;

public class TokenUtil {
public static String getMeberToken(){
return Constants.TOKEN_MEBER+"-"+ UUID.randomUUID();
}
public static String getPayToken(){
return Constants.TOKEN_PAY+"-"+ UUID.randomUUID();
}
}
  • HttpClientUtils类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package com.truly.utils;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
public class HttpClientUtil {

public static String doGet(String url, Map<String, String> param) {

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();

// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);

// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

public static String doGet(String url) {
return doGet(url, null);
}

public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return resultString;
}

public static String doPost(String url) {
return doPost(url, null);
}

public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return resultString;
}
}

Contants常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface Constants {
// 响应code
String HTTP_RES_CODE_NAME = "code";
// 响应msg
String HTTP_RES_CODE_MSG = "msg";
// 响应data
String HTTP_RES_CODE_DATA = "data";
// 响应请求成功
String HTTP_RES_CODE_200_VALUE = "success";
// 系统错误
String HTTP_RES_CODE_500_VALUE = "fial";
// 响应请求成功code
Integer HTTP_RES_CODE_200 = 200;
// 系统错误
Integer HTTP_RES_CODE_500 = 500;
}

文章作者: truly
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 truly !
  目录