master
jia 2024-02-28 13:43:24 +08:00
commit 934e15d2f4
80 changed files with 3058 additions and 0 deletions

38
.gitignore vendored 100644
View File

@ -0,0 +1,38 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
.idea/.gitignore vendored 100644
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/bwie-auth/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/bwie-common/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/bwie-gateway/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/bwie-modules/bwie-car/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/bwie-modules/bwie-es/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/bwie-modules/bwie-ord/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/bwie-modules/bwie-system/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/bwie-modules/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

14
.idea/misc.xml 100644
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

6
.idea/vcs.xml 100644
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

33
bwie-auth/pom.xml 100644
View File

@ -0,0 +1,33 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>bwie-auth</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 项目公共 依赖 -->
<dependency>
<groupId>com.bwie</groupId>
<artifactId>bwie-common</artifactId>
</dependency>
<!-- SpringBoot Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,16 @@
package com.bwie.auth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.bwie.**")
public class AuthApp {
public static void main(String[] args) {
SpringApplication.run(AuthApp.class);
}
}

View File

@ -0,0 +1,38 @@
package com.bwie.auth.controller;
import com.bwie.auth.service.AuthService;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.LoginRequest;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import org.springframework.web.bind.annotation.*;
@RestController
@ResponseBody
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@PostMapping("login")
public Result login(@RequestBody LoginRequest loginRequest){
JwtResponse login = authService.login(loginRequest);
return Result.success(login);
}
@GetMapping("info")
public User info(){
return authService.info();
}
}

View File

@ -0,0 +1,10 @@
package com.bwie.auth.service;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.LoginRequest;
import com.bwie.common.domain.response.JwtResponse;
public interface AuthService {
JwtResponse login(LoginRequest loginRequest);
User info();
}

View File

@ -0,0 +1,59 @@
package com.bwie.auth.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constant.JwtConstants;
import com.bwie.common.constant.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.LoginRequest;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.redis.RedisCache;
import com.bwie.common.remote.user.UserRemoteService;
import com.bwie.common.result.Result;
import com.bwie.common.utils.IdUtils;
import com.bwie.common.utils.JwtUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
@Service
public class AuthServiceImpl implements AuthService {
private final RedisCache redisCache;
private final HttpServletRequest request;
private final UserRemoteService userRemoteService;
public AuthServiceImpl(RedisCache redisCache, HttpServletRequest request, UserRemoteService userRemoteService) {
this.redisCache = redisCache;
this.request = request;
this.userRemoteService = userRemoteService;
}
@Override
public JwtResponse login(LoginRequest loginRequest) {
Result<User> findtel = userRemoteService.findtel(loginRequest.getUserTel());
Assert.isTrue(findtel.isSuccess(),"登陆失败");
User data = findtel.getData();
Assert.notNull(data,"电话不存在");
Assert.isTrue(data.getUserPwd().equals(loginRequest.getUserPwd()),"密码错误");
HashMap<String, Object> map = new HashMap<>();
String key = IdUtils.genId();
map.put(JwtConstants.USER_KEY,key);
String token = JwtUtils.createToken(map);
redisCache.setCacheObject(TokenConstants.LOGIN_TOKEN_KEY+key,data,TokenConstants.EXPIRATION, TimeUnit.SECONDS);
return JwtResponse.builder()
.token(token)
.expirTime(TokenConstants.EXPIRATION)
.build();
}
@Override
public User info() {
String header = request.getHeader(TokenConstants.TOKEN);
String userKey = JwtUtils.getUserKey(header);
User cacheObject = redisCache.getCacheObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
return cacheObject;
}
}

View File

@ -0,0 +1,31 @@
# Tomcat
server:
port: 9001
# Spring
spring:
main:
allow-circular-references: true
allow-bean-definition-overriding: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
application:
# 应用名称
name: bwie-auth
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 124.221.177.197:8848
config:
# 配置中心地址
server-addr: 124.221.177.197:8848
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

116
bwie-common/pom.xml 100644
View File

@ -0,0 +1,116 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>bwie-common</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- bootstrap 启动器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<!-- SpringCloud Alibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud Alibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- SpringCloud Alibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 负载均衡-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!-- SpringCloud Openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- Alibaba Fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
<!-- SpringBoot Boot Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Apache Lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- lombok依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.3</version>
</dependency>
<!-- 阿里大鱼 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.1</version>
</dependency>
<!--MQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- Mybatis-plus 配置 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.4.1</version>
</dependency>
<!-- FastJson2 json工具 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.42</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,48 @@
package com.bwie.common.config;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.Filter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* Redis使FastJson
*
* @author ruoyi
*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter(
"org.springframework", "com");
private Class<T> clazz;
public FastJson2JsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize (T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize (byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz, AUTO_TYPE_FILTER);
}
}

View File

@ -0,0 +1,30 @@
package com.bwie.common.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author DongZl
* @description: Mybatis-Plus
* @Date 2024-1-10 05:12
*/
@Configuration
public class MybatisPlusConfig {
public MybatisPlusConfig () {
System.out.println("初始化-----------");
}
/**
*
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}

View File

@ -0,0 +1,65 @@
package com.bwie.common.config;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis
*
* @author ruoyi
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public RedisTemplate<Object, Object> redisTemplate (RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
@Bean
public DefaultRedisScript<Long> limitScript () {
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(limitScriptText());
redisScript.setResultType(Long.class);
return redisScript;
}
/**
*
*/
private String limitScriptText () {
return "local key = KEYS[1]\n" +
"local count = tonumber(ARGV[1])\n" +
"local time = tonumber(ARGV[2])\n" +
"local current = redis.call('get', key);\n" +
"if current and tonumber(current) > count then\n" +
" return tonumber(current);\n" +
"end\n" +
"current = redis.call('incr', key)\n" +
"if tonumber(current) == 1 then\n" +
" redis.call('expire', key, time)\n" +
"end\n" +
"return tonumber(current);";
}
}

View File

@ -0,0 +1,18 @@
package com.bwie.common.constant;
/**
* @description:
* @author DongZl
*/
public class Constants {
/**
*
*/
public static final Integer SUCCESS = 200;
public static final String SUCCESS_MSG = "操作成功";
/**
*
*/
public static final Integer ERROR = 500;
public static final String ERROR_MSG = "操作异常";
}

View File

@ -0,0 +1,27 @@
package com.bwie.common.constant;
/**
* @author DongZl
* @description: Jwt
*/
public class JwtConstants {
/**
* ID
*/
public static final String DETAILS_USER_ID = "user_id";
/**
*
*/
public static final String DETAILS_USERNAME = "username";
/**
*
*/
public static final String USER_KEY = "user_key";
/**
*
*/
public final static String SECRET = "abcdefghijklmnopqrstuvwxyz";
}

View File

@ -0,0 +1,6 @@
package com.bwie.common.constant;
public class ServerNameConstants {
public final static String SYSTEM_NAME="bwie-system";
}

View File

@ -0,0 +1,24 @@
package com.bwie.common.constant;
/**
* @author DongZl
* @description:
*/
public class TokenConstants {
/**
* 720
*/
public final static long EXPIRATION = 720;
/**
* 120
*/
public final static long REFRESH_TIME = 120;
/**
*
*/
public final static String LOGIN_TOKEN_KEY = "login_tokens:";
/**
* token
*/
public static final String TOKEN = "token";
}

View File

@ -0,0 +1,30 @@
package com.bwie.common.domain;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName("car")
public class Car {
@TableId(value = "car_id",type = IdType.AUTO)
private Long carId;
@TableField(value = "goods_id")
private Long goodsId;
@TableField(value = "user_id")
private Long userId;
@TableField(value = "goods_num")
private Integer goodsNum;
}

View File

@ -0,0 +1,51 @@
package com.bwie.common.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName("goods")
public class Goods {
/**
* id
*/
@TableId(value = "goods_id",type = IdType.AUTO)
private Long goodsId;
//商品编码
@TableField(value = "goods_hao")
private String goodsHao;
@TableField(value = "goods_name")
private String goodsName;
@TableField(value = "goods_brand")
private String goodsBrand;
@TableField(value = "goods_intr")
private String goodsIntr;
@TableField(value = "goods_price")
private Integer goodsPrice;
@TableField(value = "goods_xin")
private Integer goodsXin;
@TableField(value = "goods_bao")
private Integer goodsBao;
@TableField(value = "goods_sync")
private Integer goodsSync;
}

View File

@ -0,0 +1,29 @@
package com.bwie.common.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class Ord {
private Long carId;
private Long goodsId;
private String goodsHao;
private String goodsName;
private String goodsBrand;
private Integer ordMoney;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private Date ordTime;
}

View File

@ -0,0 +1,33 @@
package com.bwie.common.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@TableName("user")
public class User {
@TableId(value = "user_id",type = IdType.AUTO)
private Long userId;
@TableField(value = "user_tel")
private String userTel;
@TableField(value = "user_pwd")
private String userPwd;
@TableField(value = "user_yu")
private Integer userYu;
}

View File

@ -0,0 +1,16 @@
package com.bwie.common.domain.request;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class GoodsReq {
private String goodsName;
private String goodsBrand;
}

View File

@ -0,0 +1,16 @@
package com.bwie.common.domain.request;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class LoginRequest {
private String userTel;
private String userPwd;
}

View File

@ -0,0 +1,23 @@
package com.bwie.common.domain.response;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CarShow {
private Long carId;
private Long goodsId;
private Long userId;
private Integer goodsNum;
private String goodsHao;
private String goodsName;
private Integer goodsPrice;
}

View File

@ -0,0 +1,18 @@
package com.bwie.common.domain.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class JwtResponse {
private String token;
private Long expirTime;
}

View File

@ -0,0 +1,56 @@
package com.bwie.common.handler;
import com.alibaba.fastjson.JSONObject;
import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.stream.Collectors;
@RestControllerAdvice
@Log4j2
@Configuration
public class GlobalExceptionHandle {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result<String> runtimeException(MethodArgumentNotValidException exception){
log.error("请求异常:[{}]",exception.getMessage(),exception);
return Result.error(
JSONObject.toJSONString(
exception.getBindingResult().getAllErrors()
.stream()
.map(ObjectError::getDefaultMessage)
.toArray()
)
);
// return Result.error(
// exception.getBindingResult().getAllErrors()
// .stream()
// .map(ObjectError::getDefaultMessage)
// .collect(Collectors.joining()));
}
@ExceptionHandler(value = IllegalArgumentException.class)
public Result<String> illegalArgumentExceptionHandle(IllegalArgumentException exception){
log.error("请求异常[{}]",exception.getMessage(),exception);
return Result.error(exception.getMessage());
}
}

View File

@ -0,0 +1,260 @@
package com.bwie.common.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* spring redis
*
* @author ruoyi
**/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {
@Autowired
public RedisTemplate redisTemplate;
/**
* IntegerString
*
* @param key
* @param value
*/
public <T> void setCacheObject (final String key, final T value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* IntegerString
*
* @param key
* @param value
* @param timeout
* @param timeUnit
*/
public <T> void setCacheObject (final String key, final T value, final Long timeout, final TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
*
*
* @param key Redis
* @param timeout
*
* @return true=false=
*/
public boolean expire (final String key, final long timeout) {
return expire(key, timeout, TimeUnit.SECONDS);
}
/**
*
*
* @param key Redis
* @param timeout
* @param unit
*
* @return true=false=
*/
public boolean expire (final String key, final long timeout, final TimeUnit unit) {
return Boolean.TRUE.equals(redisTemplate.expire(key, timeout, unit));
}
/**
*
*
* @param key Redis
*
* @return
*/
public long getExpire (final String key) {
return redisTemplate.getExpire(key);
}
/**
* key
*
* @param key
*
* @return true false
*/
public Boolean hasKey (String key) {
return redisTemplate.hasKey(key);
}
/**
*
*
* @param key
*
* @return
*/
public <T> T getCacheObject (final String key) {
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
*
*
* @param key
*/
public boolean deleteObject (final String key) {
return redisTemplate.delete(key);
}
/**
*
*
* @param collection
*
* @return
*/
public boolean deleteObject (final Collection collection) {
return redisTemplate.delete(collection) > 0;
}
/**
* List
*
* @param key
* @param dataList List
*
* @return
*/
public <T> long setCacheList (final String key, final List<T> dataList) {
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* list
*
* @param key
*
* @return
*/
public <T> List<T> getCacheList (final String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* Set
*
* @param key
* @param dataSet
*
* @return
*/
public <T> BoundSetOperations<String, T> setCacheSet (final String key, final Set<T> dataSet) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
for (T t : dataSet) {
setOperation.add(t);
}
return setOperation;
}
/**
* set
*
* @param key
*
* @return
*/
public <T> Set<T> getCacheSet (final String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap (final String key, final Map<String, T> dataMap) {
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* Map
*
* @param key
*
* @return
*/
public <T> Map<String, T> getCacheMap (final String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
* @param value
*/
public <T> void setCacheMapValue (final String key, final String hKey, final T value) {
redisTemplate.opsForHash().put(key, hKey, value);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
*
* @return Hash
*/
public <T> T getCacheMapValue (final String key, final String hKey) {
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* Hash
*
* @param key Redis
* @param hKeys Hash
*
* @return Hash
*/
public <T> List<T> getMultiCacheMapValue (final String key, final Collection<Object> hKeys) {
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
*
* @return
*/
public boolean deleteCacheMapValue (final String key, final String hKey) {
return redisTemplate.opsForHash().delete(key, hKey) > 0;
}
/**
*
*
* @param pattern
*
* @return
*/
public Collection<String> keys (final String pattern) {
return redisTemplate.keys(pattern);
}
}

View File

@ -0,0 +1,22 @@
package com.bwie.common.remote.user;
import com.bwie.common.constant.ServerNameConstants;
import com.bwie.common.domain.User;
import com.bwie.common.remote.user.factory.UserRemoteFactory;
import com.bwie.common.result.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(
name = ServerNameConstants.SYSTEM_NAME,
fallbackFactory = UserRemoteFactory.class
)
public interface UserRemoteService {
@PostMapping("findtel")
public Result<User> findtel(@RequestParam String userTel);
}

View File

@ -0,0 +1,23 @@
package com.bwie.common.remote.user.factory;
import com.bwie.common.domain.User;
import com.bwie.common.remote.user.UserRemoteService;
import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
@Component
@Log4j2
public class UserRemoteFactory implements FallbackFactory<UserRemoteService> {
@Override
public UserRemoteService create(Throwable cause) {
return new UserRemoteService() {
@Override
public Result<User> findtel(String userTel) {
log.error("[{}-{}]查找电话远程调用错误",userTel,cause.getMessage(),cause);
return Result.error();
}
};
}
}

View File

@ -0,0 +1,34 @@
package com.bwie.common.result;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author DongZl
* @description:
*/
@Data
public class PageResult<T> implements Serializable {
/**
*
*/
private long total;
/**
*
*/
private List<T> list;
public PageResult() {
}
public PageResult(long total, List<T> list) {
this.total = total;
this.list = list;
}
public static <T> PageResult<T> toPageResult(long total, List<T> list){
return new PageResult(total , list);
}
public static <T> Result<PageResult<T>> toResult(long total, List<T> list){
return Result.success(PageResult.toPageResult(total,list));
}
}

View File

@ -0,0 +1,63 @@
package com.bwie.common.result;
import com.bwie.common.constant.Constants;
import lombok.Data;
import java.io.Serializable;
/**
* @description:
* @author DongZl
*/
@Data
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
/** 成功 */
public static final int SUCCESS = Constants.SUCCESS;
/** 失败 */
public static final int FAIL = Constants.ERROR;
private int code;
private String msg;
private T data;
public static <T> Result<T> success() {
return restResult(null, SUCCESS, Constants.SUCCESS_MSG);
}
public static <T> Result<T> success(T data) {
return restResult(data, SUCCESS, Constants.SUCCESS_MSG);
}
public static <T> Result<T> success(T data, String msg) {
return restResult(data, SUCCESS, msg);
}
public static <T> Result<T> error() {
return restResult(null, FAIL, Constants.ERROR_MSG);
}
public static <T> Result<T> error(String msg) {
return restResult(null, FAIL, msg);
}
public static <T> Result<T> error(T data) {
return restResult(data, FAIL, Constants.ERROR_MSG);
}
public static <T> Result<T> error(T data, String msg) {
return restResult(data, FAIL, msg);
}
public static <T> Result<T> error(int code, String msg) {
return restResult(null, code, msg);
}
private static <T> Result<T> restResult(T data, int code, String msg) {
Result<T> apiResult = new Result<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
public boolean isSuccess(){
return this.code==SUCCESS;
}
public boolean isError(){
return !isSuccess();
}
}

View File

@ -0,0 +1,19 @@
package com.bwie.common.utils;
import java.util.UUID;
/**
* @author DongZl
* @description: ID
* @Date 2024-1-10 08:26
*/
public class IdUtils {
/**
* UUID
* @return UUID
*/
public static String genId(){
return UUID.randomUUID().toString().replace("-", "");
}
}

View File

@ -0,0 +1,105 @@
package com.bwie.common.utils;
import com.bwie.common.constant.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Map;
/**
* @description: Jwt
* @author DongZl
*/
public class JwtUtils {
public static String secret = JwtConstants.SECRET;
/**
*
*
* @param claims
* @return
*/
public static String createToken(Map<String, Object> claims){
String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
return token;
}
/**
*
*
* @param token
* @return
*/
public static Claims parseToken(String token){
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
/**
*
*
* @param token
* @return ID
*/
public static String getUserKey(String token){
Claims claims = parseToken(token);
return getValue(claims, JwtConstants.USER_KEY);
}
/**
*
*
* @param claims
* @return ID
*/
public static String getUserKey(Claims claims){
return getValue(claims, JwtConstants.USER_KEY);
}
/**
* ID
*
* @param token
* @return ID
*/
public static String getUserId(String token){
Claims claims = parseToken(token);
return getValue(claims, JwtConstants.DETAILS_USER_ID);
}
/**
* ID
*
* @param claims
* @return ID
*/
public static String getUserId(Claims claims){
return getValue(claims, JwtConstants.DETAILS_USER_ID);
}
/**
*
*
* @param token
* @return
*/
public static String getUserName(String token){
Claims claims = parseToken(token);
return getValue(claims, JwtConstants.DETAILS_USERNAME);
}
/**
*
*
* @param claims
* @return
*/
public static String getUserName(Claims claims){
return getValue(claims, JwtConstants.DETAILS_USERNAME);
}
/**
*
*
* @param claims
* @param key
* @return
*/
public static String getValue(Claims claims, String key){
Object obj = claims.get(key);
return obj == null ? "" : obj.toString();
}
}

View File

@ -0,0 +1,54 @@
package com.bwie.common.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
*
*
* @author ruoyi
*/
public class SecurityUtils {
/**
* BCryptPasswordEncoder
*
* @param password
*
* @return
*/
public static String encryptPassword (String password, String salt) {
return encryptMD5(password, salt);
}
/**
*
*
* @param rawPassword
* @param encodedPassword
*
* @return
*/
public static boolean matchesPassword (String rawPassword, String salt, String encodedPassword) {
return encryptMD5(rawPassword, salt).equals(encodedPassword);
}
/**
* MD5Base64
* @param password
* @return Base64
*/
public static String encryptMD5(String password, String salt) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update((password + salt).getBytes()); // 加盐处理
byte[] digest = md.digest();
return Base64.getEncoder().encodeToString(digest);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,68 @@
package com.bwie.common.utils;
import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import java.util.List;
/**
* @author DongZl
* @description:
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* *
*
* @param object Object
* @return true false
*/
public static boolean isNull(Object object) {
return object == null;
}
/**
* * Collection ListSetQueue
*
* @param coll Collection
* @return true false
*/
public static boolean isEmpty(Collection<?> coll) {
return isNull(coll) || coll.isEmpty();
}
/**
*
*
* @param str
* @param strs
* @return
*/
public static boolean matches(String str, List<String> strs) {
if (isEmpty(str) || isEmpty(strs)) {
return false;
}
for (String pattern : strs) {
if (isMatch(pattern, str))
{
return true;
}
}
return false;
}
/**
* url:
* ? ;
* * ;
* ** ;
*
* @param pattern
* @param url url
* @return
*/
public static boolean isMatch(String pattern, String url) {
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url);
}
}

View File

@ -0,0 +1,6 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.bwie.common.config.MybatisPlusConfig,\
com.bwie.common.handler.GlobalExceptionHandle,\
com.bwie.common.config.RedisConfig,\
com.bwie.common.redis.RedisCache,\
com.bwie.common.remote.user.factory.UserRemoteFactory

View File

@ -0,0 +1,44 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>bwie-gateway</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 公共模块 -->
<dependency>
<groupId>com.bwie</groupId>
<artifactId>bwie-common</artifactId>
</dependency>
<!-- 网关依赖 -->
<!-- SpringCloud GatewayApp -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- SpringCloud Alibaba Sentinel GatewayApp -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<!-- 引入阿里巴巴sentinel限流 依赖-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,14 @@
package com.bwie.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
public class GatewayApp {
public static void main(String[] args) {
SpringApplication.run(GatewayApp.class);
}
}

View File

@ -0,0 +1,71 @@
package com.bwie.gateway.config;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @deprecation:
* @author DongZl
*/
@Configuration
public class GatewaySentinelConfig {
/**
*
*/
private final List<ViewResolver> viewResolvers;
/**
*
*/
private final ServerCodecConfigurer serverCodecConfigurer;
public GatewaySentinelConfig(ObjectProvider<List<ViewResolver>> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
}
/**
* Sentinel
* @return
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
// 给 Spring Cloud GatewayApp 注册块异常处理程序。
return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
}
/**
*
*/
@PostConstruct
public void doInit() {
initGatewayRules();
}
/**
*
*/
private void initGatewayRules() {
Set<GatewayFlowRule> rules = new HashSet<>();
rules.add(new GatewayFlowRule("cloud-user")
// 限流阈值
.setCount(1)
// 统计时间窗口,单位是秒,默认是 1 秒
.setIntervalSec(5)
);
//添加到限流规则当中
GatewayRuleManager.loadRules(rules);
}
}

View File

@ -0,0 +1,32 @@
package com.bwie.gateway.config;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* @description:
* @author DongZl
*/
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "ignore")
@Data
@Log4j2
public class IgnoreWhiteConfig {
/**
*
*/
private List<String> whites = new ArrayList<>();
public void setWhites(List<String> whites) {
log.info("加载网关路径白名单:{}", JSONObject.toJSONString(whites));
this.whites = whites;
}
}

View File

@ -0,0 +1,76 @@
package com.bwie.gateway.filters;
import com.bwie.common.constant.JwtConstants;
import com.bwie.common.constant.TokenConstants;
import com.bwie.common.redis.RedisCache;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
public class AuthFilter implements GlobalFilter, Ordered {
private final RedisCache redisCache;
private final IgnoreWhiteConfig ignoreWhiteConfig;
public AuthFilter(RedisCache redisCache, IgnoreWhiteConfig ignoreWhiteConfig) {
this.redisCache = redisCache;
this.ignoreWhiteConfig = ignoreWhiteConfig;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
System.out.println("path = " + path);
HttpMethod method = request.getMethod();
System.out.println("method = " + method);
ServerHttpRequest.Builder mutate = request.mutate();
List<String> whites = ignoreWhiteConfig.getWhites();
if(StringUtils.matches(path,whites)){
return chain.filter(exchange);
}
String first = request.getHeaders().getFirst(TokenConstants.TOKEN);
if(null==first){
return GatewayUtils.errorResponse(exchange,"token不为空");
}
Claims claims = JwtUtils.parseToken(first);
if(null==claims){
return GatewayUtils.errorResponse(exchange,"token格式不正确");
}
String userKey = JwtUtils.getUserKey(claims);
if(!redisCache.hasKey(TokenConstants.LOGIN_TOKEN_KEY+userKey)){
return GatewayUtils.errorResponse(exchange,"token过期");
}
redisCache.expire(TokenConstants.LOGIN_TOKEN_KEY+userKey,30, TimeUnit.MINUTES);
// String userId = JwtUtils.getUserId(claims);
// GatewayUtils.addHander(mutate, JwtConstants.USER_KEY,userKey);
// GatewayUtils.addHander(mutate,JwtConstants.DETAILS_USER_ID,userId);
// GatewayUtils.removeHeader(mutate,TokenConstants.TOKEN);
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}

View File

@ -0,0 +1,67 @@
package com.bwie.gateway.utils;
import com.alibaba.fastjson.JSONObject;
import com.bwie.common.result.Result;
import com.bwie.common.utils.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Log4j2
public class GatewayUtils {
public static void addHander(ServerHttpRequest.Builder mutate,String key,Object value) {
if(StringUtils.isEmpty(key)){
log.warn("添加请求头参数键不可以为空");
return;
}
if(value==null){
log.warn("添加请求头参数:[{}]值为空",key);
return;
}
String string = value.toString();
mutate.header(key,string);
log.info("添加请求头参数成功 - 键:{[]},值:{[]}",key,value);
}
public static void removeHeader(ServerHttpRequest.Builder mutate, String key) {
if (StringUtils.isEmpty(key)){
log.warn("删除请求头参数键不可以为空");
return;
}
mutate.headers(httpHeaders -> httpHeaders.remove(key)).build();
log.info("删除请求头参数 - 键:[{}]",key);
}
public static Mono<Void> errorResponse(ServerWebExchange exchange,String msg){
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.OK);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE,"application/json");
Result<Object> error = Result.error(msg);
String jsonString = JSONObject.toJSONString(error);
log.error("[鉴权异常处理]请求路径:[{}],异常信息:[{}],响应结果:[{}]",
exchange.getRequest().getPath(),msg,jsonString);
DataBuffer wrap = response.bufferFactory().wrap(jsonString.getBytes());
return response.writeWith(Mono.just(wrap));
}
}

View File

@ -0,0 +1,29 @@
# Tomcat
server:
port: 18080
# Spring
spring:
application:
# 应用名称
name: bwie-gateway
profiles:
# 环境配置
active: dev
main:
# 允许使用循环引用
allow-circular-references: true
# 允许定义相同的bean对象 去覆盖原有的
allow-bean-definition-overriding: true
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 124.221.177.197:8848
config:
# 配置中心地址
server-addr: 124.221.177.197:8848
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

View File

@ -0,0 +1,63 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>bwie-car</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 系统公共 依赖 -->
<dependency>
<groupId>com.bwie</groupId>
<artifactId>bwie-common</artifactId>
</dependency>
<!-- SpringBoot Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis 依赖配置 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,15 @@
package com.bwie.car;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.bwie.car.mapper")
public class CarApp {
public static void main(String[] args) {
SpringApplication.run(CarApp.class);
}
}

View File

@ -0,0 +1,74 @@
package com.bwie.car.controller;
import com.bwie.car.mapper.CarMapper;
import com.bwie.car.service.CarService;
import com.bwie.common.constant.TokenConstants;
import com.bwie.common.domain.Car;
import com.bwie.common.domain.Ord;
import com.bwie.common.domain.User;
import com.bwie.common.domain.response.CarShow;
import com.bwie.common.redis.RedisCache;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@ResponseBody
public class CarController {
private final CarService carService;
private final RedisCache redisCache;
private final CarMapper carMapper;
private final HttpServletRequest request;
public CarController(CarService carService, RedisCache redisCache, CarMapper carMapper, HttpServletRequest request) {
this.carService = carService;
this.redisCache = redisCache;
this.carMapper = carMapper;
this.request = request;
}
@PostMapping("addcar")
public Result addcar(@RequestParam Long goodsId){
Car findgoods = carService.findgoods(goodsId, info().getUserId());
if(findgoods==null){
Car build = Car.builder()
.userId(info().getUserId())
.goodsId(goodsId)
.goodsNum(1)
.build();
carService.save(build);
}else {
findgoods.setGoodsNum(findgoods.getGoodsNum()+1);
carMapper.updateById(findgoods);
}
return Result.success();
}
@GetMapping("show")
public Result show(){
List<CarShow> show = carService.show();
return Result.success(show);
}
@PostMapping("delcar")
public Result delcar(@RequestParam Long carId){
carService.delcar(carId);
return Result.success();
}
public User info() {
String header = request.getHeader(TokenConstants.TOKEN);
String userKey = JwtUtils.getUserKey(header);
User cacheObject = redisCache.getCacheObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
return cacheObject;
}
@GetMapping("showord")
public Result showord(){
List<Ord> show = carService.showord();
return Result.success(show);
}
}

View File

@ -0,0 +1,18 @@
package com.bwie.car.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bwie.car.CarApp;
import com.bwie.common.domain.Car;
import com.bwie.common.domain.Ord;
import com.bwie.common.domain.response.CarShow;
import java.util.List;
public interface CarMapper extends BaseMapper<Car> {
List<CarShow> show(Long userId);
List<Ord> showord(Long userId);
}

View File

@ -0,0 +1,18 @@
package com.bwie.car.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bwie.common.domain.Car;
import com.bwie.common.domain.Goods;
import com.bwie.common.domain.Ord;
import com.bwie.common.domain.response.CarShow;
import java.util.List;
public interface CarService extends IService<Car> {
Car findgoods(Long goodsId, Long userId);
List<CarShow> show();
void delcar(Long carId);
List<Ord> showord();
}

View File

@ -0,0 +1,62 @@
package com.bwie.car.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.car.mapper.CarMapper;
import com.bwie.common.constant.TokenConstants;
import com.bwie.common.domain.Car;
import com.bwie.common.domain.Ord;
import com.bwie.common.domain.User;
import com.bwie.common.domain.response.CarShow;
import com.bwie.common.redis.RedisCache;
import com.bwie.common.utils.JwtUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {
private final RedisCache redisCache;
private final CarMapper carMapper;
private final HttpServletRequest request;
public CarServiceImpl(RedisCache redisCache, CarMapper carMapper, HttpServletRequest request) {
this.redisCache = redisCache;
this.carMapper = carMapper;
this.request = request;
}
@Override
public Car findgoods(Long goodsId, Long userId) {
LambdaQueryWrapper<Car> carLambdaQueryWrapper = new LambdaQueryWrapper<>();
carLambdaQueryWrapper.eq(Car::getGoodsId, goodsId);
carLambdaQueryWrapper.eq(Car::getUserId,userId);
Car car = carMapper.selectOne(carLambdaQueryWrapper);
return car;
}
@Override
public List<CarShow> show() {
List<CarShow> show = carMapper.show(info().getUserId());
return show;
}
@Override
public void delcar(Long carId) {
carMapper.deleteById(carId);
}
@Override
public List<Ord> showord() {
return carMapper.showord(info().getUserId());
}
public User info() {
String header = request.getHeader(TokenConstants.TOKEN);
String userKey = JwtUtils.getUserKey(header);
User cacheObject = redisCache.getCacheObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
return cacheObject;
}
}

View File

@ -0,0 +1,30 @@
# Tomcat
server:
port: 9003
# Spring
spring:
main:
allow-circular-references: true
allow-bean-definition-overriding: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
application:
# 应用名称
name: bwie-car
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 124.221.177.197:8848
config:
# 配置中心地址
server-addr: 124.221.177.197:8848
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bwie.car.mapper.CarMapper">
<select id="show" resultType="com.bwie.common.domain.response.CarShow">
select c.*,g.* from car c
left join goods g on g.goods_id=c.goods_id
left join user u on u.user_id=c.user_id
where u.user_id=#{userId}
</select>
<select id="showord" resultType="com.bwie.common.domain.Ord">
select * from ord o
left join car c on c.car_id=o.car_id
left join goods g on g.goods_id=c.goods_id
left join user u on u.user_id=c.user_id
where u.user_id=#{userId}
</select>
</mapper>

View File

@ -0,0 +1,69 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>bwie-es</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<elasticsearch.version>7.17.0</elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>com.bwie</groupId>
<artifactId>bwie-common</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.17.0</version>
</dependency>
<!-- SpringBoot Web-->
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis 依赖配置 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,34 @@
package com.bwie.es;
import com.bwie.common.domain.Goods;
import com.bwie.es.service.EsService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.annotation.PostConstruct;
import java.util.List;
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.bwie.es.mapper")
@EnableScheduling
public class EsApp {
private final EsService esService;
public EsApp(EsService esService) {
this.esService = esService;
}
public static void main(String[] args) {
SpringApplication.run(EsApp.class);
}
@PostConstruct
public void Sync(){
List<Goods> findall = esService.findall();
esService.BatchAdd(findall);
}
}

View File

@ -0,0 +1,25 @@
package com.bwie.es.config;
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "es")
@Data
public class InitEsRes {
private String host;
private int port;
private String scheme;
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(
RestClient.builder(new HttpHost(host,port,scheme))
);
}
}

View File

@ -0,0 +1,44 @@
package com.bwie.es.controller;
import cn.hutool.core.util.RandomUtil;
import com.bwie.common.domain.Goods;
import com.bwie.common.domain.request.GoodsReq;
import com.bwie.common.result.Result;
import com.bwie.es.service.EsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
@RestController
@ResponseBody
public class EsController {
private final EsService esService;
public EsController(EsService esService) {
this.esService = esService;
}
@PostMapping("addgoods")
public Result addgoods(@RequestBody Goods gg){
String s = RandomUtil.randomNumbers(7);
gg.setGoodsHao(s);
gg.setGoodsSync(2);
esService.save(gg);
ArrayList<Goods> goods = new ArrayList<>();
goods.add(gg);
esService.BatchAdd(goods);
return Result.success();
}
@PostMapping("show")
public Result show(@RequestBody GoodsReq req){
List<Goods> show = esService.show(req);
return Result.success(show);
}
}

View File

@ -0,0 +1,7 @@
package com.bwie.es.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bwie.common.domain.Goods;
public interface EsMapper extends BaseMapper<Goods> {
}

View File

@ -0,0 +1,13 @@
package com.bwie.es.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bwie.common.domain.Goods;
import com.bwie.common.domain.request.GoodsReq;
import java.util.List;
public interface EsService extends IService<Goods> {
List<Goods> findall();
void BatchAdd(List<Goods> gg);
List<Goods> show(GoodsReq goodsReq);
}

View File

@ -0,0 +1,128 @@
package com.bwie.es.service.impl;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.RandomUtils;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.domain.Goods;
import com.bwie.common.domain.request.GoodsReq;
import com.bwie.es.mapper.EsMapper;
import com.bwie.es.service.EsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class EsServiceImpl extends ServiceImpl<EsMapper, Goods> implements EsService {
private final EsMapper esMapper;
private final RestHighLevelClient client;
public EsServiceImpl(EsMapper esMapper, RestHighLevelClient client) {
this.esMapper = esMapper;
this.client = client;
}
@Override
public List<Goods> findall() {
LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
List<Goods> goods = esMapper.selectList(goodsLambdaQueryWrapper);
return goods;
}
@Override
public void BatchAdd(List<Goods> gg) {
BulkRequest bulkRequest = new BulkRequest();
for (Goods goods : gg) {
bulkRequest.add(new IndexRequest("goods").id(goods.getGoodsId().toString())
.source(JSON.toJSONString(goods), XContentType.JSON));
}
try {
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
Assert.isTrue(!bulk.hasFailures(),"同步失败");
for (Goods goods : gg) {
goods.setGoodsSync(1);
esMapper.updateById(goods);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public List<Goods> show(GoodsReq goodsReq) {
SearchRequest searchRequest = new SearchRequest("goods");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
if(goodsReq.getGoodsName()!=null&&!goodsReq.getGoodsName().equals("")){
boolQueryBuilder.must(QueryBuilders.matchQuery("goodsName",goodsReq.getGoodsName()).fuzziness(Fuzziness.AUTO));
}
if(goodsReq.getGoodsBrand()!=null&&!goodsReq.getGoodsBrand().equals("")){
boolQueryBuilder.must(QueryBuilders.matchQuery("goodsBrand",goodsReq.getGoodsBrand()).fuzziness(Fuzziness.AUTO));
}
searchSourceBuilder.query(boolQueryBuilder);
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("goodsName");
highlightBuilder.preTags("<span style=color:\"red\">");
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
searchRequest.source(searchSourceBuilder);
ArrayList<Goods> goods = new ArrayList<>();
try {
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits()) {
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField name = highlightFields.get("goodsName");
StringBuffer stringBuffer = new StringBuffer();
if(name!=null){
Text[] fragments = name.getFragments();
for (Text fragment : fragments) {
stringBuffer.append(fragment.toString());
}
}
String sourceAsString = hit.getSourceAsString();
Goods goods1 = JSON.parseObject(sourceAsString, Goods.class);
if(name!=null){
goods1.setGoodsName(stringBuffer.toString());
}
goods.add(goods1);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return goods;
}
}

View File

@ -0,0 +1,31 @@
package com.bwie.es.sync;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.common.domain.Goods;
import com.bwie.es.mapper.EsMapper;
import com.bwie.es.service.EsService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class MyTask {
private final EsMapper esMapper;
private final EsService esService;
public MyTask(EsMapper esMapper, EsService esService) {
this.esMapper = esMapper;
this.esService = esService;
}
@Scheduled(cron = "0/30 * * * * *")
public void checkSync(){
LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
goodsLambdaQueryWrapper.eq(Goods::getGoodsSync,2);
List<Goods> goods = esMapper.selectList(goodsLambdaQueryWrapper);
if(goods.size()>0){
esService.BatchAdd(goods);
}
}
}

View File

@ -0,0 +1,40 @@
es:
host: 124.221.177.197
port: 9200
scheme: http
# Tomcat
server:
port: 9005
# Spring
spring:
main:
allow-circular-references: true
allow-bean-definition-overriding: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
application:
# 应用名称
name: bwie-es
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 124.221.177.197:8848
config:
# 配置中心地址
server-addr: 124.221.177.197:8848
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
# 将mapper接口所在包的日志级别改成debug可以在控制台打印es
logging:
level:
org.apache.http: trace

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bwie.es.mapper.EsMapper">
</mapper>

View File

@ -0,0 +1,63 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>bwie-ord</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 系统公共 依赖 -->
<dependency>
<groupId>com.bwie</groupId>
<artifactId>bwie-common</artifactId>
</dependency>
<!-- SpringBoot Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis 依赖配置 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,4 @@
package com.bwie.ord.controller;
public class OrdController {
}

View File

@ -0,0 +1,4 @@
package com.bwie.ord.mapper;
public interface OrdMapper {
}

View File

@ -0,0 +1,4 @@
package com.bwie.ord.service;
public interface OrdService {
}

View File

@ -0,0 +1,4 @@
package com.bwie.ord.service;
public class OrdServiceImpl {
}

View File

@ -0,0 +1,30 @@
# Tomcat
server:
port: 9004
# Spring
spring:
main:
allow-circular-references: true
allow-bean-definition-overriding: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
application:
# 应用名称
name: bwie-ord
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 124.221.177.197:8848
config:
# 配置中心地址
server-addr: 124.221.177.197:8848
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

View File

@ -0,0 +1,64 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>bwie-system</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 系统公共 依赖 -->
<dependency>
<groupId>com.bwie</groupId>
<artifactId>bwie-common</artifactId>
</dependency>
<!-- SpringBoot Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis 依赖配置 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,15 @@
package com.bwie.system;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.bwie.system.mapper")
public class SysApp {
public static void main(String[] args) {
SpringApplication.run(SysApp.class);
}
}

View File

@ -0,0 +1,25 @@
package com.bwie.system.controller;
import com.bwie.common.domain.User;
import com.bwie.common.result.Result;
import com.bwie.system.service.SysService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@ResponseBody
public class SysController {
private final SysService service;
public SysController(SysService service) {
this.service = service;
}
@PostMapping("findtel")
public Result<User> findtel(@RequestParam String userTel){
User findtel = service.findtel(userTel);
return Result.success(findtel);
}
}

View File

@ -0,0 +1,8 @@
package com.bwie.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bwie.common.domain.User;
import com.bwie.common.remote.user.UserRemoteService;
public interface SysMapper extends BaseMapper<User> {
}

View File

@ -0,0 +1,9 @@
package com.bwie.system.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bwie.common.domain.User;
import com.bwie.common.remote.user.UserRemoteService;
public interface SysService extends IService<User> {
User findtel(String userTel);
}

View File

@ -0,0 +1,24 @@
package com.bwie.system.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.domain.User;
import com.bwie.system.mapper.SysMapper;
import org.springframework.stereotype.Service;
@Service
public class SysServiceImpl extends ServiceImpl<SysMapper, User> implements SysService{
private final SysMapper sysMapper;
public SysServiceImpl(SysMapper sysMapper) {
this.sysMapper = sysMapper;
}
@Override
public User findtel(String userTel) {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUserTel,userTel);
User user = sysMapper.selectOne(queryWrapper);
return user;
}
}

View File

@ -0,0 +1,30 @@
# Tomcat
server:
port: 9002
# Spring
spring:
main:
allow-circular-references: true
allow-bean-definition-overriding: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
application:
# 应用名称
name: bwie-system
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 124.221.177.197:8848
config:
# 配置中心地址
server-addr: 124.221.177.197:8848
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bwie.system.mapper.SysMapper">
</mapper>

View File

@ -0,0 +1,20 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>bwie-modules</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

70
pom.xml 100644
View File

@ -0,0 +1,70 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bwie</groupId>
<artifactId>test_week1</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>bwie-common</module>
<module>bwie-auth</module>
<module>bwie-gateway</module>
<module>bwie-modules</module>
<module>bwie-modules/bwie-system</module>
<module>bwie-modules/bwie-es</module>
<module>bwie-modules/bwie-car</module>
<module>bwie-modules/bwie-ord</module>
</modules>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- 规定SpringBoot版本 -->
<!-- 父级pom文件 主要用于规定项目依赖的各个版本,用于进行项目版本约束 -->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.6.2</version>
<relativePath/>
</parent>
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<!-- SpringCloud 微服务 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- SpringCloud Alibaba 微服务 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2021.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Alibaba Nacos 配置 -->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>2.0.4</version>
</dependency>
<!-- 系统公共 依赖 版本号定义-->
<dependency>
<groupId>com.bwie</groupId>
<artifactId>bwie-common</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>