From e0fd0c98222418ac82efc3f7b13ae11a61f2dda1 Mon Sep 17 00:00:00 2001 From: yovinchen Date: Mon, 25 Sep 2023 09:17:53 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=8F=E7=A8=8B=E5=BA=8F=E7=99=BB=E5=BD=95?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/compiler.xml | 2 + .idea/encodings.xml | 1 + .idea/inspectionProfiles/Project_Default.xml | 3 + .idea/vcs.xml | 1 - atguigu-tuan/common/http.interceptor.js | 2 +- atguigu-tuan/pages/login/login.vue | 10 +- .../atguigu/ssyx/common/utils/JwtHelper.java | 64 ++++ .../ssyx/common/auth/AuthContextHolder.java | 50 +++ .../auth/LoginMvcConfigurerAdapter.java | 30 ++ .../common/auth/UserLoginInterceptor.java | 53 +++ .../ssyx/common/config/RedisConfig.java | 105 ++++++ .../ssyx/common/constant/RedisConst.java | 49 +++ guigu-ssyx-parent/service/pom.xml | 1 + .../service/service-user/Dockerfile | 5 + .../service/service-user/pom.xml | 20 ++ .../atguigu/ssyx/ServiceUserApplication.java | 22 ++ .../user/controller/WeixinApiController.java | 41 +++ .../ssyx/user/mapper/LeaderMapper.java | 17 + .../ssyx/user/mapper/UserDeliveryMapper.java | 17 + .../atguigu/ssyx/user/mapper/UserMapper.java | 17 + .../ssyx/user/service/LoginWxService.java | 100 ++++++ .../ssyx/user/service/UserService.java | 46 +++ .../user/service/impl/UserServiceImpl.java | 97 ++++++ .../user/utils/ConstantPropertiesUtil.java | 29 ++ .../ssyx/user/utils/HttpClientUtils.java | 317 ++++++++++++++++++ .../src/main/resources/application-dev.yml | 36 ++ .../src/main/resources/application.yml | 11 + 27 files changed, 1139 insertions(+), 7 deletions(-) create mode 100644 guigu-ssyx-parent/common/common-util/src/main/java/com/atguigu/ssyx/common/utils/JwtHelper.java create mode 100644 guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/AuthContextHolder.java create mode 100644 guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/LoginMvcConfigurerAdapter.java create mode 100644 guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/UserLoginInterceptor.java create mode 100644 guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/config/RedisConfig.java create mode 100644 guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/constant/RedisConst.java create mode 100644 guigu-ssyx-parent/service/service-user/Dockerfile create mode 100644 guigu-ssyx-parent/service/service-user/pom.xml create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/ServiceUserApplication.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/controller/WeixinApiController.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/LeaderMapper.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/UserDeliveryMapper.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/UserMapper.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/LoginWxService.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/UserService.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/impl/UserServiceImpl.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/utils/ConstantPropertiesUtil.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/utils/HttpClientUtils.java create mode 100644 guigu-ssyx-parent/service/service-user/src/main/resources/application-dev.yml create mode 100644 guigu-ssyx-parent/service/service-user/src/main/resources/application.yml diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 1a380cb..dfc8203 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -12,6 +12,7 @@ + @@ -35,6 +36,7 @@ + diff --git a/.idea/encodings.xml b/.idea/encodings.xml index d903963..f8295f9 100644 --- a/.idea/encodings.xml +++ b/.idea/encodings.xml @@ -16,6 +16,7 @@ + diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml index 03d9549..648d6c6 100644 --- a/.idea/inspectionProfiles/Project_Default.xml +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -2,5 +2,8 @@ \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 676e256..94a25f7 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,6 +2,5 @@ - \ No newline at end of file diff --git a/atguigu-tuan/common/http.interceptor.js b/atguigu-tuan/common/http.interceptor.js index fc1fc02..7e2e168 100644 --- a/atguigu-tuan/common/http.interceptor.js +++ b/atguigu-tuan/common/http.interceptor.js @@ -1,7 +1,7 @@ const install = (Vue, vm) => { Vue.prototype.$u.http.setConfig({ //baseUrl: 'https://gmall-prod.atguigu.cn/api', - baseUrl: 'http://ggkt2.vipgz1.91tunnel.com/api', + baseUrl: 'http://localhost:8200/api', loadingText: '请求中...', // 请求loading中的文字提示 loadingTime: 800, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透 diff --git a/atguigu-tuan/pages/login/login.vue b/atguigu-tuan/pages/login/login.vue index 63abf98..8955d6e 100644 --- a/atguigu-tuan/pages/login/login.vue +++ b/atguigu-tuan/pages/login/login.vue @@ -59,11 +59,11 @@ export default { data: result.token, success: async () => { // 更新用户信息 - await this.$u.api.postUpdateUser({ - sex, - photoUrl, - nickName - }); + // await this.$u.api.postUpdateUser({ + // sex, + // photoUrl, + // nickName + // }); // 路由跳转至首页 uni.reLaunch({ url: '/pages/index/index', diff --git a/guigu-ssyx-parent/common/common-util/src/main/java/com/atguigu/ssyx/common/utils/JwtHelper.java b/guigu-ssyx-parent/common/common-util/src/main/java/com/atguigu/ssyx/common/utils/JwtHelper.java new file mode 100644 index 0000000..90ec248 --- /dev/null +++ b/guigu-ssyx-parent/common/common-util/src/main/java/com/atguigu/ssyx/common/utils/JwtHelper.java @@ -0,0 +1,64 @@ +package com.atguigu.ssyx.common.utils; + +import io.jsonwebtoken.*; +import org.springframework.util.StringUtils; + +import java.util.Date; + +/** + * ClassName: JwtHelper + * Package: com.atguigu.ssyx.common.utils + * + * @author yovinchen + * @Create 2023/9/22 15:50 + */ +public class JwtHelper { + + private static final long tokenExpiration = 365L * 24 * 60 * 60 * 1000; + private static final String tokenSignKey = "ssyx"; + + public static String createToken(Long userId, String userName) { + String token = Jwts.builder() + .setSubject("ssyx-USER") + .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) + .claim("userId", userId) + .claim("userName", userName) + .signWith(SignatureAlgorithm.HS512, tokenSignKey) + .compressWith(CompressionCodecs.GZIP) + .compact(); + return token; + } + + public static Long getUserId(String token) { + if (StringUtils.isEmpty(token)) return null; + + Jws claimsJws = Jwts.parser() + .setSigningKey(tokenSignKey) + .parseClaimsJws(token); + Claims claims = claimsJws.getBody(); + Integer userId = (Integer) claims.get("userId"); + return userId.longValue(); + // return 1L; + } + + public static String getUserName(String token) { + if (StringUtils.isEmpty(token)) return ""; + + Jws claimsJws = Jwts.parser() + .setSigningKey(tokenSignKey) + .parseClaimsJws(token); + Claims claims = claimsJws.getBody(); + return (String) claims.get("userName"); + } + + public static void removeToken(String token) { + //jwttoken无需删除,客户端扔掉即可。 + } + + public static void main(String[] args) { + String token = JwtHelper.createToken(7L, "admin"); + System.out.println(token); + System.out.println(JwtHelper.getUserId(token)); + System.out.println(JwtHelper.getUserName(token)); + } +} diff --git a/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/AuthContextHolder.java b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/AuthContextHolder.java new file mode 100644 index 0000000..4e2ca42 --- /dev/null +++ b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/AuthContextHolder.java @@ -0,0 +1,50 @@ +package com.atguigu.ssyx.common.auth; + +import com.atguigu.ssyx.vo.user.UserLoginVo; + +/** + * ClassName: AuthContextHolder + * Package: com.atguigu.ssyx.common.auth + * + * @author yovinchen + * @Create 2023/9/22 17:40 + */ +//ThreadLocal工具类 +public class AuthContextHolder { + + //用户id + private static final ThreadLocal userId = new ThreadLocal<>(); + + //用户仓库id + private static final ThreadLocal wareId = new ThreadLocal<>(); + + //用户信息对象 + private static final ThreadLocal userLoginVo = new ThreadLocal<>(); + + public static Long getUserId() { + return userId.get(); + } + + //userId操作的方法 + public static void setUserId(Long _userId) { + userId.set(_userId); + } + + public static Long getWareId() { + return wareId.get(); + } + + public static void setWareId(Long _wareId) { + wareId.set(_wareId); + } + + public static UserLoginVo getUserLoginVo() { + return userLoginVo.get(); + } + + public static void setUserLoginVo(UserLoginVo _userLoginVo) { + userLoginVo.set(_userLoginVo); + } + + +} diff --git a/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/LoginMvcConfigurerAdapter.java b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/LoginMvcConfigurerAdapter.java new file mode 100644 index 0000000..214ad8e --- /dev/null +++ b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/LoginMvcConfigurerAdapter.java @@ -0,0 +1,30 @@ +package com.atguigu.ssyx.common.auth; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; + +import javax.annotation.Resource; + +/** + * ClassName: LoginMvcConfigurerAdapter + * Package: com.atguigu.ssyx.common.auth + * + * @author yovinchen + * @Create 2023/9/22 23:58 + */ +@Configuration +public class LoginMvcConfigurerAdapter extends WebMvcConfigurationSupport { + + @Resource + private RedisTemplate redisTemplate; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new UserLoginInterceptor(redisTemplate)) + .addPathPatterns("/api/**") + .excludePathPatterns("/api/user/weixin/wxLogin/*"); + super.addInterceptors(registry); + } +} diff --git a/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/UserLoginInterceptor.java b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/UserLoginInterceptor.java new file mode 100644 index 0000000..c405123 --- /dev/null +++ b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/auth/UserLoginInterceptor.java @@ -0,0 +1,53 @@ +package com.atguigu.ssyx.common.auth; + +import com.atguigu.ssyx.common.constant.RedisConst; +import com.atguigu.ssyx.common.utils.JwtHelper; +import com.atguigu.ssyx.vo.user.UserLoginVo; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * ClassName: UserLoginInterceptor + * Package: com.atguigu.ssyx.common.auth + * + * @author yovinchen + * @Create 2023/9/22 23:47 + */ +public class UserLoginInterceptor implements HandlerInterceptor { + + private final RedisTemplate redisTemplate; + + public UserLoginInterceptor(RedisTemplate redisTemplate) { + this.redisTemplate = redisTemplate; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + this.getUserLoginVo(request); + return true; + } + + private void getUserLoginVo(HttpServletRequest request) { + //从请求头获取token + String token = request.getHeader("token"); + + //判断token不为空 + if (!StringUtils.isEmpty(token)) { + //从token获取userId + Long userId = JwtHelper.getUserId(token); + //根据userId到Redis获取用户信息 + UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue() + .get(RedisConst.USER_LOGIN_KEY_PREFIX + userId); + //获取数据放到ThreadLocal里面 + if (userLoginVo != null) { + AuthContextHolder.setUserId(userLoginVo.getUserId()); + AuthContextHolder.setWareId(userLoginVo.getWareId()); + AuthContextHolder.setUserLoginVo(userLoginVo); + } + } + } +} diff --git a/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/config/RedisConfig.java b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/config/RedisConfig.java new file mode 100644 index 0000000..da30210 --- /dev/null +++ b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/config/RedisConfig.java @@ -0,0 +1,105 @@ +package com.atguigu.ssyx.common.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import java.lang.reflect.Method; +import java.time.Duration; + +/** + * ClassName: RedisConfig + * Package: com.atguigu.ssyx.common.config + * Redis配置类 + * + * @author yovinchen + * @Create 2023/9/22 15:55 + */ + +@Configuration +@EnableCaching +public class RedisConfig { + + // 使用默认标签做缓存 + @Bean + public KeyGenerator wiselyKeyGenerator() { + return new KeyGenerator() { + @Override + public Object generate(Object target, Method method, Object... params) { + StringBuilder sb = new StringBuilder(); + sb.append(target.getClass() + .getName()); + sb.append(method.getName()); + for (Object obj : params) { + sb.append(obj.toString()); + } + return sb.toString(); + } + }; + } + + // 声明模板 + /* + ref = 表示引用 + value = 具体的值 + + + + */ + // 工具类: + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setConnectionFactory(redisConnectionFactory); + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(objectMapper); + // 将Redis 中 string ,hash 数据类型,自动序列化! + redisTemplate.setKeySerializer(new StringRedisSerializer()); + redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); + redisTemplate.setHashKeySerializer(new StringRedisSerializer()); + redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); + + redisTemplate.afterPropertiesSet(); + return redisTemplate; + } + + @Bean + public CacheManager cacheManager(RedisConnectionFactory factory) { + RedisSerializer redisSerializer = new StringRedisSerializer(); + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); + + //解决查询缓存转换异常的问题 + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + + // 配置序列化(解决乱码的问题),过期时间600秒 + RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(Duration.ofDays(365)) + .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) + .disableCachingNullValues(); + + RedisCacheManager cacheManager = RedisCacheManager.builder(factory) + .cacheDefaults(config) + .build(); + return cacheManager; + } +} diff --git a/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/constant/RedisConst.java b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/constant/RedisConst.java new file mode 100644 index 0000000..beaca2e --- /dev/null +++ b/guigu-ssyx-parent/common/service-util/src/main/java/com/atguigu/ssyx/common/constant/RedisConst.java @@ -0,0 +1,49 @@ +package com.atguigu.ssyx.common.constant; + +/** + * ClassName: RedisConst + * Package: com.atguigu.ssyx.common.constant + * Redis常量配置类 + * + * @author yovinchen + * @Create 2023/9/22 15:57 + */ +public class RedisConst { + + public static final String SKUKEY_PREFIX = "sku:"; + public static final String SKUKEY_SUFFIX = ":info"; + //单位:秒 + public static final long SKUKEY_TIMEOUT = 24 * 60 * 60; + // 定义变量,记录空对象的缓存过期时间 缓存穿透key的过期时间 + public static final long SKUKEY_TEMPORARY_TIMEOUT = 10 * 60; + + //单位:秒 尝试获取锁的最大等待时间 + public static final long SKULOCK_EXPIRE_PX1 = 1; + //单位:秒 锁的持有时间 + public static final long SKULOCK_EXPIRE_PX2 = 1; + public static final String SKULOCK_SUFFIX = ":lock"; + + public static final String USER_KEY_PREFIX = "user:"; + public static final String USER_CART_KEY_SUFFIX = ":cart"; + public static final long USER_CART_EXPIRE = 60 * 60 * 24 * 7; + public static final String SROCK_INFO = "stock:info:"; + public static final String ORDER_REPEAT = "order:repeat:"; + + //用户登录 + public static final String USER_LOGIN_KEY_PREFIX = "user:login:"; + public static final String ADMIN_LOGIN_KEY_PREFIX = "admin:login:"; + // public static final String userinfoKey_suffix = ":info"; + public static final int USERKEY_TIMEOUT = 365; + public static final String ORDER_SKU_MAP = "order:sku:"; + + //秒杀商品前缀 + public static final String SECKILL_TIME_MAP = "seckill:time:map"; + public static final String SECKILL_SKU_MAP = "seckill:sku:map"; + public static final String SECKILL_SKU_LIST = "seckill:sku:list:"; + public static final String SECKILL_USER_MAP = "seckill:user:map:"; + public static final String SECKILL_ORDERS_USERS = "seckill:orders:users"; + public static final String SECKILL_STOCK_PREFIX = "seckill:stock:"; + public static final String SECKILL_USER = "seckill:user:"; + //用户锁定时间 单位:秒 + public static final int SECKILL__TIMEOUT = 60 * 60; +} diff --git a/guigu-ssyx-parent/service/pom.xml b/guigu-ssyx-parent/service/pom.xml index dd3d5af..ed2a3e4 100644 --- a/guigu-ssyx-parent/service/pom.xml +++ b/guigu-ssyx-parent/service/pom.xml @@ -17,6 +17,7 @@ service-product service-search service-activity + service-user diff --git a/guigu-ssyx-parent/service/service-user/Dockerfile b/guigu-ssyx-parent/service/service-user/Dockerfile new file mode 100644 index 0000000..f4e1a79 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/Dockerfile @@ -0,0 +1,5 @@ +FROM openjdk:8-jdk-alpine +LABEL authors="yovinchen" +VOLUME /tmp +ADD ./target/service-user.jar service-user.jar +ENTRYPOINT ["java","-jar","/service-user.jar", "&"] diff --git a/guigu-ssyx-parent/service/service-user/pom.xml b/guigu-ssyx-parent/service/service-user/pom.xml new file mode 100644 index 0000000..b3749c1 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + com.atguigu + service + 1.0-SNAPSHOT + + + service-user + + + 8 + 8 + UTF-8 + + + diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/ServiceUserApplication.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/ServiceUserApplication.java new file mode 100644 index 0000000..e4912dd --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/ServiceUserApplication.java @@ -0,0 +1,22 @@ +package com.atguigu.ssyx; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.openfeign.EnableFeignClients; + +/** + * ClassName: ServiceUserApplication + * Package: com.atguigu.ssyx + * + * @author yovinchen + * @Create 2023/9/22 15:39 + */ +@SpringBootApplication +@EnableDiscoveryClient +@EnableFeignClients +public class ServiceUserApplication { + public static void main(String[] args) { + SpringApplication.run(ServiceUserApplication.class, args); + } +} diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/controller/WeixinApiController.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/controller/WeixinApiController.java new file mode 100644 index 0000000..22065e6 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/controller/WeixinApiController.java @@ -0,0 +1,41 @@ +package com.atguigu.ssyx.user.controller; + +import com.atguigu.ssyx.common.result.Result; +import com.atguigu.ssyx.model.user.User; +import com.atguigu.ssyx.user.service.LoginWxService; +import com.atguigu.ssyx.user.service.UserService; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * ClassName: WeixinApiController + * Package: com.atguigu.ssyx.user.controller + * + * @author yovinchen + * @Create 2023/9/22 16:23 + */ +@RestController +@RequestMapping("/api/user/weixin") +public class WeixinApiController { + + @Autowired + private LoginWxService loginWxService; + + @Autowired + private UserService userService; + + //用户微信授权登录 + @ApiOperation(value = "微信登录获取openid(小程序)") + @GetMapping("/wxLogin/{code}") + public Result loginWx(@PathVariable String code) { + return Result.ok(loginWxService.loginWx(code)); + } + + @PostMapping("/auth/updateUser") + @ApiOperation(value = "更新用户昵称与头像") + public Result updateUser(@RequestBody User user) { + userService.updateUser(user); + return Result.ok(null); + } +} diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/LeaderMapper.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/LeaderMapper.java new file mode 100644 index 0000000..dcd8bda --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/LeaderMapper.java @@ -0,0 +1,17 @@ +package com.atguigu.ssyx.user.mapper; + +import com.atguigu.ssyx.model.user.Leader; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.springframework.stereotype.Repository; + +/** + * ClassName: LeaderMapper + * Package: com.atguigu.ssyx.user.mapper + * + * @author yovinchen + * @Create 2023/9/22 16:57 + */ +@Repository +public interface LeaderMapper extends BaseMapper { +} + diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/UserDeliveryMapper.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/UserDeliveryMapper.java new file mode 100644 index 0000000..b5f32ca --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/UserDeliveryMapper.java @@ -0,0 +1,17 @@ +package com.atguigu.ssyx.user.mapper; + +import com.atguigu.ssyx.model.user.UserDelivery; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.springframework.stereotype.Repository; + +/** + * ClassName: UserDeliveryMapper + * Package: com.atguigu.ssyx.user.mapper + * + * @author yovinchen + * @Create 2023/9/22 16:57 + */ +@Repository +public interface UserDeliveryMapper extends BaseMapper { +} + diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/UserMapper.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/UserMapper.java new file mode 100644 index 0000000..8550e45 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/mapper/UserMapper.java @@ -0,0 +1,17 @@ +package com.atguigu.ssyx.user.mapper; + +import com.atguigu.ssyx.model.user.User; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.springframework.stereotype.Repository; + + +/** + * ClassName: UserMapper + * Package: com.atguigu.ssyx.user.mapper + * + * @author yovinchen + * @Create 2023/9/22 16:50 + */ +@Repository +public interface UserMapper extends BaseMapper { +} diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/LoginWxService.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/LoginWxService.java new file mode 100644 index 0000000..1f7855c --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/LoginWxService.java @@ -0,0 +1,100 @@ +package com.atguigu.ssyx.user.service; + +import com.alibaba.fastjson.JSONObject; +import com.atguigu.ssyx.common.constant.RedisConst; +import com.atguigu.ssyx.common.exception.SsyxException; +import com.atguigu.ssyx.common.result.ResultCodeEnum; +import com.atguigu.ssyx.common.utils.JwtHelper; +import com.atguigu.ssyx.enums.UserType; +import com.atguigu.ssyx.model.user.User; +import com.atguigu.ssyx.user.utils.ConstantPropertiesUtil; +import com.atguigu.ssyx.user.utils.HttpClientUtils; +import com.atguigu.ssyx.vo.user.LeaderAddressVo; +import com.atguigu.ssyx.vo.user.UserLoginVo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * ClassName: LoginWxService + * Package: com.atguigu.ssyx.user.service + * + * @author yovinchen + * @Create 2023/9/22 17:08 + */ +@Service +public class LoginWxService { + + @Autowired + private UserService userService; + + @Autowired + private RedisTemplate redisTemplate; + + + public Map loginWx(String code) { + //1 得到微信返回code临时票据值 + //2 拿着code + 小程序id + 小程序秘钥 请求微信接口服务 + //// 使用HttpClient工具请求 + //小程序id + String wxOpenAppId = ConstantPropertiesUtil.WX_OPEN_APP_ID; + //小程序秘钥 + String wxOpenAppSecret = ConstantPropertiesUtil.WX_OPEN_APP_SECRET; + //get请求 + //拼接请求地址+参数 + /// 地址?name=value&name1=value1 + String url = "https://api.weixin.qq.com/sns/jscode2session" + "?appid=%s" + "&secret=%s" + "&js_code=%s" + "&grant_type=authorization_code"; + String tokenUrl = String.format(url, wxOpenAppId, wxOpenAppSecret, code); + //HttpClient发送get请求 + String result = null; + try { + result = HttpClientUtils.get(tokenUrl); + } catch (Exception e) { + throw new SsyxException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD); + } + + //3 请求微信接口服务,返回两个值 session_key 和 openid + //// openId是你微信唯一标识 + JSONObject jsonObject = JSONObject.parseObject(result); + String session_key = jsonObject.getString("session_key"); + String openid = jsonObject.getString("openid"); + + //4 添加微信用户信息到数据库里面 + //// 操作user表 + //// 判断是否是第一次使用微信授权登录:如何判断?openId + User user = userService.getUserByOpenId(openid); + if (user == null) { + user = new User(); + user.setOpenId(openid); + user.setNickName(openid); + user.setPhotoUrl(""); + user.setUserType(UserType.USER); + user.setIsNew(0); + userService.save(user); + } + + //5 根据userId查询提货点和团长信息 + ////提货点 user表 user_delivery表 + ////团长 leader表 + LeaderAddressVo leaderAddressVo = userService.getLeaderAddressByUserId(user.getId()); + + //6 使用JWT工具根据userId和userName生成token字符串 + String token = JwtHelper.createToken(user.getId(), user.getNickName()); + + //7 获取当前登录用户信息,放到Redis里面,设置有效时间 + UserLoginVo userLoginVo = userService.getUserLoginVo(user.getId()); + redisTemplate.opsForValue() + .set(RedisConst.USER_LOGIN_KEY_PREFIX + user.getId(), userLoginVo, RedisConst.USERKEY_TIMEOUT, TimeUnit.DAYS); + + //8 需要数据封装到map返回 + Map map = new HashMap<>(); + map.put("user", user); + map.put("token", token); + map.put("leaderAddressVo", leaderAddressVo); + return map; + } +} diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/UserService.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/UserService.java new file mode 100644 index 0000000..d83cd73 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/UserService.java @@ -0,0 +1,46 @@ +package com.atguigu.ssyx.user.service; + +import com.atguigu.ssyx.model.user.User; +import com.atguigu.ssyx.vo.user.LeaderAddressVo; +import com.atguigu.ssyx.vo.user.UserLoginVo; +import com.baomidou.mybatisplus.extension.service.IService; + +/** + * ClassName: UserService + * Package: com.atguigu.ssyx.user.service + * + * @author yovinchen + * @Create 2023/9/22 16:33 + */ +public interface UserService extends IService { + /** + * 根据微信openid获取用户信息 + * + * @param openid + * @return + */ + User getUserByOpenId(String openid); + + /** + * 根据userId查询提货点和团长信息 + * + * @param id + * @return + */ + LeaderAddressVo getLeaderAddressByUserId(Long id); + + /** + * 获取当前登录用户信息 + * + * @param id + * @return + */ + UserLoginVo getUserLoginVo(Long id); + + /** + * 更新用户昵称与头像 + * + * @param user + */ + void updateUser(User user); +} diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/impl/UserServiceImpl.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..84fa20a --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/service/impl/UserServiceImpl.java @@ -0,0 +1,97 @@ +package com.atguigu.ssyx.user.service.impl; + +import com.atguigu.ssyx.common.auth.AuthContextHolder; +import com.atguigu.ssyx.model.user.Leader; +import com.atguigu.ssyx.model.user.User; +import com.atguigu.ssyx.model.user.UserDelivery; +import com.atguigu.ssyx.user.mapper.LeaderMapper; +import com.atguigu.ssyx.user.mapper.UserDeliveryMapper; +import com.atguigu.ssyx.user.mapper.UserMapper; +import com.atguigu.ssyx.user.service.UserService; +import com.atguigu.ssyx.vo.user.LeaderAddressVo; +import com.atguigu.ssyx.vo.user.UserLoginVo; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * ClassName: UserServiceImpl + * Package: com.atguigu.ssyx.user.service.impl + * + * @author yovinchen + * @Create 2023/9/22 16:34 + */ +@Service +public class UserServiceImpl extends ServiceImpl implements UserService { + @Autowired + private UserDeliveryMapper userDeliveryMapper; + + @Autowired + private LeaderMapper leaderMapper; + + //// 判断是否是第一次使用微信授权登录:如何判断?openId + @Override + public User getUserByOpenId(String openid) { + User user = baseMapper.selectOne(new LambdaQueryWrapper().eq(User::getOpenId, openid)); + return user; + } + + //5 根据userId查询提货点和团长信息 + @Override + public LeaderAddressVo getLeaderAddressByUserId(Long userId) { + //根据userId查询用户默认的团长id + UserDelivery userDelivery = userDeliveryMapper.selectOne(new LambdaQueryWrapper().eq(UserDelivery::getUserId, userId) + .eq(UserDelivery::getIsDefault, 1)); + if (userDelivery == null) { + return null; + } + //拿着上面查询团长id查询leader表查询团长其他信息 + Leader leader = leaderMapper.selectById(userDelivery.getLeaderId()); + //封装数据到LeaderAddressVo + LeaderAddressVo leaderAddressVo = new LeaderAddressVo(); + BeanUtils.copyProperties(leader, leaderAddressVo); + leaderAddressVo.setUserId(userId); + leaderAddressVo.setLeaderId(leader.getId()); + leaderAddressVo.setLeaderName(leader.getName()); + leaderAddressVo.setLeaderPhone(leader.getPhone()); + leaderAddressVo.setWareId(userDelivery.getWareId()); + leaderAddressVo.setStorePath(leader.getStorePath()); + return leaderAddressVo; + } + + //7 获取当前登录用户信息, + @Override + public UserLoginVo getUserLoginVo(Long id) { + User user = baseMapper.selectById(id); + UserLoginVo userLoginVo = new UserLoginVo(); + userLoginVo.setUserId(id); + userLoginVo.setNickName(user.getNickName()); + userLoginVo.setPhotoUrl(user.getPhotoUrl()); + userLoginVo.setIsNew(user.getIsNew()); + userLoginVo.setOpenId(user.getOpenId()); + + UserDelivery userDelivery = userDeliveryMapper.selectOne(new LambdaQueryWrapper().eq(UserDelivery::getUserId, id) + .eq(UserDelivery::getIsDefault, 1)); + if (userDelivery != null) { + userLoginVo.setLeaderId(userDelivery.getLeaderId()); + userLoginVo.setWareId(userDelivery.getWareId()); + } else { + userLoginVo.setLeaderId(1L); + userLoginVo.setWareId(1L); + } + return userLoginVo; + } + + @Override + public void updateUser(User user) { + //获取当前登录用户id + User user1 = baseMapper.selectById(AuthContextHolder.getUserId()); + //把昵称更新为微信用户 + user1.setNickName(user.getNickName() + .replaceAll("[ue000-uefff]", "*")); + user1.setPhotoUrl(user.getPhotoUrl()); + baseMapper.updateById(user1); + } +} diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/utils/ConstantPropertiesUtil.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/utils/ConstantPropertiesUtil.java new file mode 100644 index 0000000..9a69d53 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/utils/ConstantPropertiesUtil.java @@ -0,0 +1,29 @@ +package com.atguigu.ssyx.user.utils; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * ClassName: ConstantPropertiesUtil + * Package: com.atguigu.ssyx.user.utils + * + * @author yovinchen + * @Create 2023/9/22 16:19 + */ +@Component +public class ConstantPropertiesUtil implements InitializingBean { + + public static String WX_OPEN_APP_ID; + public static String WX_OPEN_APP_SECRET; + @Value("${wx.open.app_id}") + private String appId; + @Value("${wx.open.app_secret}") + private String appSecret; + + @Override + public void afterPropertiesSet() throws Exception { + WX_OPEN_APP_ID = appId; + WX_OPEN_APP_SECRET = appSecret; + } +} diff --git a/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/utils/HttpClientUtils.java b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/utils/HttpClientUtils.java new file mode 100644 index 0000000..76a12f3 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/java/com/atguigu/ssyx/user/utils/HttpClientUtils.java @@ -0,0 +1,317 @@ +package com.atguigu.ssyx.user.utils; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.config.RequestConfig.Builder; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.conn.ssl.X509HostnameVerifier; +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.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicNameValuePair; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.security.GeneralSecurityException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ClassName: HttpClientUtils + * Package: com.atguigu.ssyx.user.utils + * + * @author yovinchen + * @Create 2023/9/22 16:20 + */ +public class HttpClientUtils { + + public static final int connTimeout = 10000; + public static final int readTimeout = 10000; + public static final String charset = "UTF-8"; + private static HttpClient client = null; + + static { + PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); + cm.setMaxTotal(128); + cm.setDefaultMaxPerRoute(128); + client = HttpClients.custom() + .setConnectionManager(cm) + .build(); + } + + public static String postParameters(String url, String parameterStr) throws Exception { + return post(url, parameterStr, "application/x-www-form-urlencoded", charset, connTimeout, readTimeout); + } + + public static String postParameters(String url, String parameterStr, String charset, Integer connTimeout, Integer readTimeout) throws Exception { + return post(url, parameterStr, "application/x-www-form-urlencoded", charset, connTimeout, readTimeout); + } + + public static String postParameters(String url, Map params) throws Exception { + return postForm(url, params, null, connTimeout, readTimeout); + } + + public static String postParameters(String url, Map params, Integer connTimeout, Integer readTimeout) throws Exception { + return postForm(url, params, null, connTimeout, readTimeout); + } + + public static String get(String url) throws Exception { + return get(url, charset, null, null); + } + + public static String get(String url, String charset) throws Exception { + return get(url, charset, connTimeout, readTimeout); + } + + /** + * 发送一个 Post 请求, 使用指定的字符集编码. + * + * @param url + * @param body RequestBody + * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3 + * @param charset 编码 + * @param connTimeout 建立链接超时时间,毫秒. + * @param readTimeout 响应超时时间,毫秒. + * @return ResponseBody, 使用指定的字符集编码. + * @throws ConnectTimeoutException 建立链接超时异常 + * @throws SocketTimeoutException 响应超时 + * @throws Exception + */ + public static String post(String url, String body, String mimeType, String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception { + HttpClient client = null; + HttpPost post = new HttpPost(url); + String result = ""; + try { + if (StringUtils.isNotBlank(body)) { + HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset)); + post.setEntity(entity); + } + // 设置参数 + Builder customReqConf = RequestConfig.custom(); + if (connTimeout != null) { + customReqConf.setConnectTimeout(connTimeout); + } + if (readTimeout != null) { + customReqConf.setSocketTimeout(readTimeout); + } + post.setConfig(customReqConf.build()); + + HttpResponse res; + if (url.startsWith("https")) { + // 执行 Https 请求. + client = createSSLInsecureClient(); + res = client.execute(post); + } else { + // 执行 Http 请求. + client = HttpClientUtils.client; + res = client.execute(post); + } + result = IOUtils.toString(res.getEntity() + .getContent(), charset); + } finally { + post.releaseConnection(); + if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) { + ((CloseableHttpClient) client).close(); + } + } + return result; + } + + /** + * 提交form表单 + * + * @param url + * @param params + * @param connTimeout + * @param readTimeout + * @return + * @throws ConnectTimeoutException + * @throws SocketTimeoutException + * @throws Exception + */ + public static String postForm(String url, Map params, Map headers, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception { + + HttpClient client = null; + HttpPost post = new HttpPost(url); + try { + if (params != null && !params.isEmpty()) { + List formParams = new ArrayList(); + Set> entrySet = params.entrySet(); + for (Entry entry : entrySet) { + formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8); + post.setEntity(entity); + } + + if (headers != null && !headers.isEmpty()) { + for (Entry entry : headers.entrySet()) { + post.addHeader(entry.getKey(), entry.getValue()); + } + } + // 设置参数 + Builder customReqConf = RequestConfig.custom(); + if (connTimeout != null) { + customReqConf.setConnectTimeout(connTimeout); + } + if (readTimeout != null) { + customReqConf.setSocketTimeout(readTimeout); + } + post.setConfig(customReqConf.build()); + HttpResponse res = null; + if (url.startsWith("https")) { + // 执行 Https 请求. + client = createSSLInsecureClient(); + res = client.execute(post); + } else { + // 执行 Http 请求. + client = HttpClientUtils.client; + res = client.execute(post); + } + return IOUtils.toString(res.getEntity() + .getContent(), "UTF-8"); + } finally { + post.releaseConnection(); + if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) { + ((CloseableHttpClient) client).close(); + } + } + } + + /** + * 发送一个 GET 请求 + * + * @param url + * @param charset + * @param connTimeout 建立链接超时时间,毫秒. + * @param readTimeout 响应超时时间,毫秒. + * @return + * @throws ConnectTimeoutException 建立链接超时 + * @throws SocketTimeoutException 响应超时 + * @throws Exception + */ + public static String get(String url, String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception { + + HttpClient client = null; + HttpGet get = new HttpGet(url); + String result = ""; + try { + // 设置参数 + Builder customReqConf = RequestConfig.custom(); + if (connTimeout != null) { + customReqConf.setConnectTimeout(connTimeout); + } + if (readTimeout != null) { + customReqConf.setSocketTimeout(readTimeout); + } + get.setConfig(customReqConf.build()); + + HttpResponse res = null; + + if (url.startsWith("https")) { + // 执行 Https 请求. + client = createSSLInsecureClient(); + res = client.execute(get); + } else { + // 执行 Http 请求. + client = HttpClientUtils.client; + res = client.execute(get); + } + result = IOUtils.toString(res.getEntity() + .getContent(), charset); + } finally { + get.releaseConnection(); + if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) { + ((CloseableHttpClient) client).close(); + } + } + return result; + } + + /** + * 从 response 里获取 charset + * + * @param ressponse + * @return + */ + @SuppressWarnings("unused") + private static String getCharsetFromResponse(HttpResponse ressponse) { + // Content-Type:text/html; charset=GBK + if (ressponse.getEntity() != null && ressponse.getEntity() + .getContentType() != null && ressponse.getEntity() + .getContentType() + .getValue() != null) { + String contentType = ressponse.getEntity() + .getContentType() + .getValue(); + if (contentType.contains("charset=")) { + return contentType.substring(contentType.indexOf("charset=") + 8); + } + } + return null; + } + + /** + * 创建 SSL连接 + * + * @return + * @throws GeneralSecurityException + */ + private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException { + try { + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } + }) + .build(); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { + + @Override + public boolean verify(String arg0, SSLSession arg1) { + return true; + } + + @Override + public void verify(String host, SSLSocket ssl) throws IOException { + } + + @Override + public void verify(String host, X509Certificate cert) throws SSLException { + } + + @Override + public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { + } + }); + return HttpClients.custom() + .setSSLSocketFactory(sslsf) + .build(); + } catch (GeneralSecurityException e) { + throw e; + } + } +} diff --git a/guigu-ssyx-parent/service/service-user/src/main/resources/application-dev.yml b/guigu-ssyx-parent/service/service-user/src/main/resources/application-dev.yml new file mode 100644 index 0000000..75452c5 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/resources/application-dev.yml @@ -0,0 +1,36 @@ +server: + port: 8206 + +mybatis-plus: + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + type-enums-package: com.atguigu.ssyx.enums + +spring: + datasource: + type: com.zaxxer.hikari.HikariDataSource + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://82.157.68.223:3306/shequ-user?characterEncoding=utf-8&useSSL=false + username: shequ-user + password: shequ-user + jackson: + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + redis: + host: 82.157.68.223 + port: 6379 + database: 0 + timeout: 1800000 + password: + lettuce: + pool: + max-active: 20 #最大连接数 + max-wait: -1 #最大阻塞等待时间(负数表示没限制) + max-idle: 5 #最大空闲 + min-idle: 0 #最小空闲 +wx: + open: + # 小程序微信公众平台appId + app_id: wx2edefe049c6a37b9 + # 小程序微信公众平台api秘钥 + app_secret: 1cb2b7aec97a28f0cdf4b74defa1792a diff --git a/guigu-ssyx-parent/service/service-user/src/main/resources/application.yml b/guigu-ssyx-parent/service/service-user/src/main/resources/application.yml new file mode 100644 index 0000000..f8cff58 --- /dev/null +++ b/guigu-ssyx-parent/service/service-user/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + application: + name: service-user + profiles: + active: dev + cloud: + nacos: + discovery: + server-addr: 82.157.68.223:8848 + username: nacos + password: nacos