lzy 1 week ago
commit
3c54d3b0f7

+ 33 - 0
Marketplace/.gitignore

@@ -0,0 +1,33 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/

+ 161 - 0
Marketplace/pom.xml

@@ -0,0 +1,161 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>com.dt</groupId>
+    <artifactId>Marketplace</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <name>Marketplace</name>
+    <description>Marketplace</description>
+    <properties>
+        <java.version>1.8</java.version>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+        <spring-boot.version>2.7.6</spring-boot.version>
+    </properties>
+    <dependencies>
+
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-boot-starter</artifactId>
+            <version>3.5.4</version>
+        </dependency>
+
+
+        <dependency>
+            <groupId>org.redisson</groupId>
+            <artifactId>redisson-spring-boot-starter</artifactId>
+            <version>3.21.3</version>
+        </dependency>
+
+
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.9.0</version>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.83</version> <!-- 版本可能不同 -->
+        </dependency>
+
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-boot-starter</artifactId>
+            <version>3.5.4</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+        <!-- Hibernate Validator (Bean Validation 实现) -->
+        <dependency>
+            <groupId>org.hibernate.validator</groupId>
+            <artifactId>hibernate-validator</artifactId>
+            <version>6.2.0.Final</version>
+        </dependency>
+        <!-- 验证API -->
+        <dependency>
+            <groupId>javax.validation</groupId>
+            <artifactId>validation-api</artifactId>
+            <version>2.0.1.Final</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>3.15.1</version>
+        </dependency>
+
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.mybatis.spring.boot</groupId>
+            <artifactId>mybatis-spring-boot-starter</artifactId>
+            <version>2.3.0</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.mysql</groupId>
+            <artifactId>mysql-connector-j</artifactId>
+            <scope>runtime</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-dependencies</artifactId>
+                <version>${spring-boot.version}</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>3.8.1</version>
+                <configuration>
+                    <source>1.8</source>
+                    <target>1.8</target>
+                    <encoding>UTF-8</encoding>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <version>${spring-boot.version}</version>
+                <configuration>
+                    <mainClass>com.dt.MarketplaceApplication</mainClass>
+                    <skip>true</skip>
+                </configuration>
+                <executions>
+                    <execution>
+                        <id>repackage</id>
+                        <goals>
+                            <goal>repackage</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 13 - 0
Marketplace/src/main/java/com/dt/MarketplaceApplication.java

@@ -0,0 +1,13 @@
+package com.dt;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class MarketplaceApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(MarketplaceApplication.class, args);
+    }
+
+}

+ 27 - 0
Marketplace/src/main/java/com/dt/config/ApiException.java

@@ -0,0 +1,27 @@
+package com.dt.config;
+
+
+import lombok.Data;
+
+@Data
+public class ApiException extends RuntimeException{
+	
+	public Integer code;
+	public String msg;
+	public ApiException(BaseExceptionEnum baseExceptionEnum) {
+		super(baseExceptionEnum.getMessage());
+		this.code = baseExceptionEnum.getCode();
+		this.msg = baseExceptionEnum.getMessage();
+	}
+	public ApiException(String message) {
+		super(message);
+		this.code=101;
+		this.msg=message;
+	}
+	public ApiException(Integer code, String message) {
+		super(message);
+		this.code=code;
+		this.msg=message;
+	}
+
+}

+ 18 - 0
Marketplace/src/main/java/com/dt/config/BaseExceptionEnum.java

@@ -0,0 +1,18 @@
+package com.dt.config;
+
+/**
+ * 抽象接口
+ *
+ */
+public interface BaseExceptionEnum {
+
+    /**
+     * 获取异常编码
+     */
+    Integer getCode();
+
+    /**
+     * 获取异常信息
+     */
+    String getMessage();
+}

+ 6 - 0
Marketplace/src/main/java/com/dt/config/CommonContants.java

@@ -0,0 +1,6 @@
+package com.dt.config;
+
+public class CommonContants {
+    public static final String PREFIX_TOKEN="token:";
+    public static final ThreadLocal<String> local=new ThreadLocal<>();
+}

+ 11 - 0
Marketplace/src/main/java/com/dt/config/NonLoginRequired.java

@@ -0,0 +1,11 @@
+package com.dt.config;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.METHOD)
+public @interface NonLoginRequired {
+}

+ 21 - 0
Marketplace/src/main/java/com/dt/config/WebMvcConfig.java

@@ -0,0 +1,21 @@
+package com.dt.config;
+
+
+import com.dt.intercepter.AuthIntercepter;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@Configuration
+public class WebMvcConfig implements WebMvcConfigurer {
+
+    @Autowired
+    private AuthIntercepter authIntercepter;
+
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        registry.addInterceptor(authIntercepter)
+                .addPathPatterns("/**");
+    }
+}

+ 78 - 0
Marketplace/src/main/java/com/dt/intercepter/AuthIntercepter.java

@@ -0,0 +1,78 @@
+package com.dt.intercepter;
+
+
+
+import com.dt.config.ApiException;
+import com.dt.config.CommonContants;
+import com.dt.config.NonLoginRequired;
+import com.dt.util.TokenUtils;
+import lombok.extern.slf4j.Slf4j;
+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 org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.HandlerInterceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Method;
+
+@Component
+@Slf4j
+public class AuthIntercepter implements HandlerInterceptor {
+
+
+    @Autowired
+    private StringRedisTemplate stringRedisTemplate;
+
+
+
+    public final static  String Token="token";
+
+    public AuthIntercepter() {
+
+
+    }
+
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handle)
+    {
+        String token  = request.getHeader(Token);
+
+        String requestURI = request.getRequestURI();
+        if (requestURI.equals("/user/login")){
+            return true;
+        }
+        try {
+            if (!(handle instanceof HandlerMethod))
+            {
+                return true;
+            }
+            HandlerMethod handlerMethod=(HandlerMethod)handle;
+            Method method = handlerMethod.getMethod();
+            NonLoginRequired loginRequired = method.getAnnotation(NonLoginRequired.class);
+            if (loginRequired!=null)
+            {
+                return true;
+            }
+            if (StringUtils.isEmpty(token))
+            {
+                log.info("token为空");
+                throw new Exception("token错误,请重新登录");
+            }
+            Long userId = TokenUtils.getUserId(token);
+            log.info("userId",userId);
+            String s = stringRedisTemplate.opsForValue().get(userId);
+            if (s.equals(token))
+            {
+                log.info("*************用户不存在");
+                throw new ApiException(101,"token错误");
+            }
+            CommonContants.local.set(userId.toString());
+        } catch (Exception e) {
+            log.info("调用了异常通知",e.getMessage());
+            throw new RuntimeException(e);
+        }
+        return true;
+    }
+}

+ 52 - 0
Marketplace/src/main/java/com/dt/oss/OSSService.java

@@ -0,0 +1,52 @@
+package com.dt.oss;
+
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClientBuilder;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.UUID;
+
+@Service
+
+public class OSSService {
+
+    @Value("${oss.endpoint}")
+    private String endpoint;
+
+    @Value("${oss.accessKeyId}")
+    private String accessKeyId;
+
+    @Value("${oss.accessKeySecret}")
+    private String accessKeySecret;
+
+    @Value("${oss.bucketName}")
+    private String bucketName;
+
+    public String upload(MultipartFile file) throws IOException {
+        // 生成唯一文件名
+        String originalFilename = file.getOriginalFilename();
+        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
+        String objectName = UUID.randomUUID().toString() ;
+        Date date = new Date();
+        date.setTime(date.getTime() + 1000 * 60 * 60 * 24 * 7);
+        objectName = date.getTime() + objectName.substring(2,10)+ fileExtension;
+        System.out.println(objectName);
+        // 上传到OSS
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+        try {
+            ossClient.putObject(bucketName, objectName, file.getInputStream());
+            return generateUrl(objectName);
+        } finally {
+            ossClient.shutdown();
+        }
+    }
+
+    private String generateUrl(String objectName) {
+        return "https://" + bucketName + "." + endpoint.replace("https://", "") + "/" + objectName;
+    }
+}

+ 31 - 0
Marketplace/src/main/java/com/dt/oss/controller/OSSController.java

@@ -0,0 +1,31 @@
+package com.dt.oss.controller;
+
+import com.dt.config.NonLoginRequired;
+import com.dt.oss.OSSService;
+import com.sun.istack.internal.NotNull;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import java.io.IOException;
+
+@RequestMapping("/oss")
+@RestController
+public class OSSController {
+
+
+
+    @Resource
+    private OSSService ossService;
+
+
+    @RequestMapping("/uupload")
+    @NonLoginRequired
+    public String upload(MultipartFile file) throws IOException {
+        return ossService.upload(file);
+    }
+
+
+}

+ 67 - 0
Marketplace/src/main/java/com/dt/util/Md5Utils.java

@@ -0,0 +1,67 @@
+package com.dt.util;
+import java.security.MessageDigest;
+import java.util.Random;
+/**
+ * @version 1.0
+ * @Author ZZX
+ * @Date 2022/12/19 17:35
+ */
+public class Md5Utils {
+    /**
+     * md5 加密
+     *
+     * @param saltAndPwd
+     * @return
+     */
+    public static String encode(String saltAndPwd) {
+        try {
+            return
+                    toHex(MessageDigest.getInstance("MD5").digest(saltAndPwd.getBytes("UTF-8"))).toLowerCase();
+        } catch (Exception e) {
+            throw new RuntimeException("md5 加密", e);
+        }
+    }
+    /**
+     * 十六进制字符
+     */
+    private static final char[] HEX_CHARS =
+            "0123456789ABCDEF".toCharArray();
+    /**
+     * 转换为十六进制字符串
+     *
+     * @param bytes
+     * @return
+     */
+    private static String toHex(byte[] bytes) {
+        StringBuilder str = new StringBuilder(bytes.length * 2);
+        final int fifteen = 0x0f;//十六进制中的 15
+        for (byte b : bytes) {//byte 为 32 位
+            str.append(HEX_CHARS[(b >> 4) & fifteen]);//获取第 25 位到第 28 位的二进制数
+            str.append(HEX_CHARS[b & fifteen]);//获取第 29 位到第 32 位的二进制数
+        }
+        return str.toString();
+    }
+    /**
+     * 随机生成10位密码盐
+     * @return
+     */
+    public static String getSalt() {
+        char[] chars =
+                ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +
+                        "1234567890!@#$%^&*()_+").toCharArray();
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < 30; i++) {
+            //Random().nextInt()返回值为[0,n)
+            char aChar = chars[new Random().nextInt(chars.length)];
+            sb.append(aChar);
+        }
+        return sb.toString();
+    }
+    // 测试
+    public static void main(String[] args) {
+        String salt = getSalt();// get the salt
+        String pwd = "123456";// the inital pwd
+        String saltPwd = encode(salt + pwd);//calculate the new-pwd by the salt and the inital pwd
+        System.out.println(saltPwd);// sout to test
+    }
+}

+ 64 - 0
Marketplace/src/main/java/com/dt/util/RRException.java

@@ -0,0 +1,64 @@
+package com.dt.util;
+
+/**
+ * 增强版业务异常类
+ * 包含错误码、错误信息、可选数据载荷
+ */
+public class RRException extends RuntimeException {
+
+
+    private final int code;
+    private final String msg;
+    private transient Object data; // transient避免序列化问题
+
+    // 常用构造方法
+    public RRException(int code, String msg) {
+        super(msg);
+        this.code = code;
+        this.msg = msg;
+    }
+
+    public RRException(int code, String msg, Object data) {
+        super(msg);
+        this.code = code;
+        this.msg = msg;
+        this.data = data;
+    }
+
+    public RRException(int code, String msg, Throwable cause) {
+        super(msg, cause);
+        this.code = code;
+        this.msg = msg;
+    }
+
+    // 快速创建异常的静态工厂方法
+    public static RRException of(int code, String msg) {
+        return new RRException(code, msg);
+    }
+
+    public static RRException of(int code, String msg, Object data) {
+        return new RRException(code, msg, data);
+    }
+
+    // Getter 方法
+    public int getCode() {
+        return code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public Object getData() {
+        return data;
+    }
+
+    @Override
+    public String toString() {
+        return "RRException{" +
+                "code=" + code +
+                ", msg='" + msg + '\'' +
+                ", data=" + data +
+                '}';
+    }
+}

+ 113 - 0
Marketplace/src/main/java/com/dt/util/TokenUtils.java

@@ -0,0 +1,113 @@
+package com.dt.util;
+
+
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.JwtBuilder;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.bind.DatatypeConverter;
+import java.security.Key;
+import java.util.Date;
+
+/**
+ * 生成Token工具类
+ */
+public class TokenUtils {
+
+    /**
+     * 签名秘钥
+     */
+    public static final String SECRET = "cjyfutu1688";
+
+    /**
+     * 生成token
+     * @param id 一般传入userName
+     * @return
+     */
+    public static String createJwtToken(String id){
+        String issuer = "www.futureading.com";
+        String subject = "65532781@qq.com";
+        long ttlMillis = System.currentTimeMillis();
+        return createJwtToken(id, issuer, subject, ttlMillis);
+    }
+
+    /**
+     * 生成Token
+     *
+     * @param id
+     *            编号
+     * @param issuer
+     *            该JWT的签发者,是否使用是可选的
+     * @param subject
+     *            该JWT所面向的用户,是否使用是可选的;
+     * @param ttlMillis
+     *            签发时间
+     * @return token String
+     */
+    public static String createJwtToken(String id, String issuer, String subject, long ttlMillis) {
+
+        // 签名算法 ,将对token进行签名
+        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
+
+        // 生成签发时间
+        long nowMillis = System.currentTimeMillis();
+        Date now = new Date(nowMillis);
+
+        // 通过秘钥签名JWT
+        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
+        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
+
+        // Let's set the JWT Claims
+        JwtBuilder builder = Jwts.builder().setId(id)
+                .setIssuedAt(now)
+                .setSubject(subject)
+                .setIssuer(issuer)
+                .signWith(signatureAlgorithm, signingKey);
+
+        // if it has been specified, let's add the expiration
+        if (ttlMillis >= 0) {
+            long expMillis = nowMillis + ttlMillis;
+            Date exp = new Date(expMillis);
+            builder.setExpiration(exp);
+        }
+
+        // Builds the JWT and serializes it to a compact, URL-safe string
+        return builder.compact();
+
+    }
+
+    // Sample method to validate and read the JWT
+    public static Claims parseJWT(String jwt) {
+        // This line will throw an exception if it is not a signed JWS (as expected)
+        Claims claims = Jwts.parser()
+                .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
+                .parseClaimsJws(jwt).getBody();
+        return claims;
+    }
+
+    public static Long getUserId(String token){
+        Claims claims = null;
+        try {
+            claims = TokenUtils.parseJWT(token);
+        } catch (Exception e) {
+            throw new RRException(101, "token错误,请重新登录");
+        }
+
+        if(null==claims) {
+            throw new RRException(101, "token错误,请重新登录");
+        }
+        String id = claims.getId();
+        Long userId=Long.valueOf(id);
+
+        return userId;
+
+
+    }
+
+    public static void main(String[] args) {
+        System.out.println(TokenUtils.createJwtToken("admin"));
+    }
+}

+ 56 - 0
Marketplace/src/main/resources/application.yml

@@ -0,0 +1,56 @@
+server:
+  port: 3333
+
+spring:
+  datasource:
+    driver-class-name: com.mysql.cj.jdbc.Driver
+    url: jdbc:mysql://101.200.59.170:3306/child_care_system?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8
+    username: root
+    password: liziyang
+  web:
+    resources:
+      static-locations: file:///D:/img/
+  redis:
+    host: 101.200.59.170
+    port: 6379
+    database: 0
+mybatis-plus:
+  type-aliases-package: cn.zhentao.pojo
+  configuration:
+    map-underscore-to-camel-case: true
+    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
+  mapper-locations: classpath:mapper/*.xml
+logging:
+  level:
+    cn:
+      zhentao: debug
+
+
+
+#  kafka:
+#    producer:
+#      key-serializer: org.apache.kafka.common.serialization.StringSerializer
+#      value-serializer: org.apache.kafka.common.serialization.StringSerializer
+#      batch-size: 16384
+#      buffer-memory: 33554432
+#      retries: 3
+#      linger: 1
+#    bootstrap-servers: localhost:9092
+#    consumer:
+#      group-id: sms_group
+#      auto-offset-reset: latest #latest
+#      enable-auto-commit: false
+#      auto-commit-interval: 100
+#      max-poll-records: 500
+#      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
+#      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
+
+oss:
+  endpoint: oss-cn-beijing.aliyuncs.com
+  accessKeyId: LTAI5tSRDXqvdLAaeiw2NAcq
+  accessKeySecret: 73gVomAk5W4Q7UPxqQKOgQp1TyK6A0
+  bucketName: lzy8
+
+
+
+

+ 13 - 0
Marketplace/src/test/java/com/dt/MarketplaceApplicationTests.java

@@ -0,0 +1,13 @@
+package com.dt;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class MarketplaceApplicationTests {
+
+    @Test
+    void contextLoads() {
+    }
+
+}