diff --git a/01-basic/data-structure/pom.xml b/01-basic/data-structure/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..3ca91cc1a5bc159f5bde50a6101c62058aec1d4a --- /dev/null +++ b/01-basic/data-structure/pom.xml @@ -0,0 +1,27 @@ + + + + 01-basic + org.example + 1.0-SNAPSHOT + + 4.0.0 + + com.novice + data-structure + + + 17 + 17 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + \ No newline at end of file diff --git a/01-basic/data-structure/src/main/java/com/novice/com/novice/algorithm/BinarySearch.java b/01-basic/data-structure/src/main/java/com/novice/com/novice/algorithm/BinarySearch.java new file mode 100644 index 0000000000000000000000000000000000000000..af7b793c50319749e3749431c7beee40bd39884c --- /dev/null +++ b/01-basic/data-structure/src/main/java/com/novice/com/novice/algorithm/BinarySearch.java @@ -0,0 +1,56 @@ +package com.novice.com.novice.algorithm; + +/** + * 二分查找: 有序数组,查询target 返回索引值 + * 找不到返回-1 + *

+ * ## 整体思路: + *

+ * 1.首先设置了i、j两个指针,这两个指针呢,指向的是这个数字的两端, + *

+ * 2.当i在j的左侧,或者是它俩相等的时候,就循环来执行逻辑, + *

+ * 3.然后i在j的右侧,表示没有找到,返回失败的结果 + *

+ * 4.中间这个循环,就是取i和j的中间值,把它的中间值跟目标值进行一个比较, + *

+ * 5.如果目标在中间值的左侧,接下来还应该在左边找,所以让右边界缩小到中间索引减一位置, + *

+ * 6.如果目标在中间值的右侧,目标在右侧,就改变左边界,让它增大成为中间索引位置右边一个位置, + *

+ * 7.循环缩小范围,直到中间值跟目标值相等,返回这个中间索引 + * + * @author novice + * @Date 2024/03/31 + */ +public class BinarySearch { + public static void main(String[] args) { + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int target = 1; + int index = binarySearch(arr, target); + System.out.println(index); + } + + /** + * 二分查找 + * + * @param arr 加勒比海盗 + * @param target 目标 + * @return int + */ + private static int binarySearch(int[] arr, int target) { + int left = 0; + int right = arr.length - 1; + while (left <= right) { + int mid = (left + right) / 2; + if (arr[mid] == target) { // 正合适 + return mid; + } else if (arr[mid] < target) { // 中间值小于目标值,说明目标值在右边 + left = mid + 1; + } else if(arr[mid] > target){ // 中间值大于目标值,说明目标值在左边 + right = mid - 1; + } + } + return -1; + } +} diff --git a/01-basic/pom.xml b/01-basic/pom.xml index f73761ec641f9a9d9721d892f8c809722dda353e..188588d50e9f71c61f136d445c4798ce1a3abe35 100644 --- a/01-basic/pom.xml +++ b/01-basic/pom.xml @@ -3,15 +3,31 @@ 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"> 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + org.example 01-basic + pom 1.0-SNAPSHOT + + data-structure + 17 17 + + + org.springframework.boot + spring-boot-starter-test + + + \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/assert/img.png b/02-framework/cloud-demo/eureka-demo/assert/img.png new file mode 100644 index 0000000000000000000000000000000000000000..5c45b47c338ac3ff9050ed79280d741b9348a38c Binary files /dev/null and b/02-framework/cloud-demo/eureka-demo/assert/img.png differ diff --git a/02-framework/cloud-demo/eureka-demo/assert/img2.png b/02-framework/cloud-demo/eureka-demo/assert/img2.png new file mode 100644 index 0000000000000000000000000000000000000000..f96410bc3e5f020b3f5924bbb35eec6e57345a8a Binary files /dev/null and b/02-framework/cloud-demo/eureka-demo/assert/img2.png differ diff --git a/02-framework/cloud-demo/eureka-demo/assert/ribbon.md b/02-framework/cloud-demo/eureka-demo/assert/ribbon.md new file mode 100644 index 0000000000000000000000000000000000000000..08e0c3bd0d9bd5c0296c36f0d0e9dac402586ae6 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/assert/ribbon.md @@ -0,0 +1,3 @@ +![img.png](img.png) + +![img.png](img2.png) \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/pom.xml b/02-framework/cloud-demo/eureka-demo/eureka-client-order/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..fc4e3a5f03fa19c9bd9b53e705fec8336d93b0e8 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/pom.xml @@ -0,0 +1,50 @@ + + + + eureka-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + eureka-client-order + + + 17 + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + + cn.hutool + hutool-all + + + + mysql + mysql-connector-java + + + + com.alibaba + druid-spring-boot-starter + + + + com.baomidou + mybatis-plus-boot-starter + + + + \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/OrderClientApp.java b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/OrderClientApp.java new file mode 100644 index 0000000000000000000000000000000000000000..29548a570422e6ffd89703c026eaaccb4a557211 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/OrderClientApp.java @@ -0,0 +1,24 @@ +package com.novice; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.context.annotation.Bean; +import org.springframework.web.client.RestTemplate; + +@EnableEurekaClient +@SpringBootApplication +@MapperScan(basePackages = "com.novice.mapper") +public class OrderClientApp { + public static void main(String[] args) { + SpringApplication.run(OrderClientApp.class, args); + } + + @Bean + @LoadBalanced + public RestTemplate getRestTemplate() { + return new RestTemplate(); + } +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/controller/OrderController.java b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/controller/OrderController.java new file mode 100644 index 0000000000000000000000000000000000000000..462a9da4d399a9f6e6ba8f4def5a9da6c9f8f051 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/controller/OrderController.java @@ -0,0 +1,20 @@ +package com.novice.controller; + +import com.novice.domain.entity.Order; +import com.novice.service.IOrderService; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("/order") +public class OrderController { + @Resource + private IOrderService orderService; + @RequestMapping("/{orderId}") + public Order getOrderById(@PathVariable("orderId") Long orderId) { + return orderService.getOrderById(orderId); + } +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/entity/Order.java b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/entity/Order.java new file mode 100644 index 0000000000000000000000000000000000000000..5d09ae9457c9db8c8603f0964b8a714324e4e41c --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/entity/Order.java @@ -0,0 +1,36 @@ +package com.novice.domain.entity; + +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 com.novice.domain.pojo.User; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName("t_order") +public class Order { + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "goods_name") + private String goodsName; + + @TableField(value = "count") + private Integer count; + + @TableField(value = "price") + private BigDecimal price; + + @TableField(value = "user_id") + private Long userId; + + @TableField(exist = false) + private User user; +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/pojo/User.java b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/pojo/User.java new file mode 100644 index 0000000000000000000000000000000000000000..7d623445788ff37abe3dac8e5a44aab9aa9024b4 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/pojo/User.java @@ -0,0 +1,20 @@ +package com.novice.domain.pojo; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class User { + private Long id; + + private String username; + + private Integer age; + + private String addr; +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/readme.md b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..8e4f42ba86747c7b8a6b31894b1514f10c3ae63d --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/domain/readme.md @@ -0,0 +1,4 @@ +pojo文件夹中:简单无规则Java对象,只有属性+get+set方法 +entity文件夹中是存放数据库实体对象类 +vo、params文件夹是存放请求入参数 +dto文件夹是存放请求返回参数 \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/mapper/OrderMapper.java b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/mapper/OrderMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..4b30d403f8567447df028cda3c6c45bf72b837c1 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/mapper/OrderMapper.java @@ -0,0 +1,7 @@ +package com.novice.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.novice.domain.entity.Order; + +public interface OrderMapper extends BaseMapper { +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/service/IOrderService.java b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/service/IOrderService.java new file mode 100644 index 0000000000000000000000000000000000000000..8df4b04ee899f667e74a3cdfd337a7fe6cce95f3 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/service/IOrderService.java @@ -0,0 +1,8 @@ +package com.novice.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.novice.domain.entity.Order; + +public interface IOrderService extends IService { + Order getOrderById(Long orderId); +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/service/impl/IOrderServiceImpl.java b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/service/impl/IOrderServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..79e211d1bd63ee550dbe52bcff11f304051cf104 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/java/com/novice/service/impl/IOrderServiceImpl.java @@ -0,0 +1,30 @@ +package com.novice.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.novice.domain.entity.Order; +import com.novice.domain.pojo.User; +import com.novice.mapper.OrderMapper; +import com.novice.service.IOrderService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; + + +@Service +@Transactional(rollbackFor = Exception.class) +public class IOrderServiceImpl extends ServiceImpl implements IOrderService { + @Resource + private RestTemplate restTemplate; + + @Override + public Order getOrderById(Long orderId) { + Order order = baseMapper.selectById(orderId); + String url = "http://userservice/user/" + order.getUserId(); + // 利用restTemplate 发起远程调用,获取用户信息 + User forObject = restTemplate.getForObject(url, User.class); + order.setUser(forObject); + return order; + } +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/resources/application-druid.yml b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/resources/application-druid.yml new file mode 100644 index 0000000000000000000000000000000000000000..f575be053849dc5d8916774bf54e027dfc4d7da8 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/resources/application-druid.yml @@ -0,0 +1,64 @@ +mybatis-plus: + # 搜索指定包别名 + type-aliases-package: com.novice.**.domain.entity + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapper-locations: classpath*:mapper/**/*Mapper.xml + configuration: + map-underscore-to-camel-case: true #自动驼峰映射 + +#日志配置 +logging: + level: + com.novice.mapper: debug +spring: + # 数据源配置 + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/db-order?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: 123456 + druid: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置连接超时时间 + connectTimeout: 30000 + # 配置网络超时时间 + socketTimeout: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: ruoyi + login-password: 123456 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/resources/application.yml b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..1cbf4395e17f600932f6866612abd1bb50d6d6e3 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-order/src/main/resources/application.yml @@ -0,0 +1,24 @@ +server: + port: 8302 + +spring: + profiles: + active: druid + application: + name: orderservice + +eureka: + client: + service-url: + defaultZone: http://47.109.145.220:8300/eureka/ + +# 在调用userservice时,使用这个负责均衡规则配置---》轮询 +userservice: + ribbon: + NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule + +ribbon: + eager-load: + enabled: true # 开启饥饿加载 + clients: # 指定饥饿加载的客户端 + - userservice \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/pom.xml b/02-framework/cloud-demo/eureka-demo/eureka-client-user/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..20a092a48f3d505ea4945d9a748242216a73a22f --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/pom.xml @@ -0,0 +1,50 @@ + + + + eureka-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + eureka-client-user + + + 17 + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + + cn.hutool + hutool-all + + + + mysql + mysql-connector-java + + + + com.alibaba + druid-spring-boot-starter + + + + com.baomidou + mybatis-plus-boot-starter + + + + \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/UserClientApp.java b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/UserClientApp.java new file mode 100644 index 0000000000000000000000000000000000000000..e15a8db908db385afbb5e7f68e980875b2d8934d --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/UserClientApp.java @@ -0,0 +1,16 @@ +package com.novice; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@EnableEurekaClient +@SpringBootApplication +@MapperScan(basePackages = "com.novice.mapper") +public class UserClientApp { + public static void main(String[] args) + { + SpringApplication.run(UserClientApp.class,args); + } +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/controller/UserController.java b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/controller/UserController.java new file mode 100644 index 0000000000000000000000000000000000000000..41b94669fc521746257a8c28b752ea378c5d863a --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/controller/UserController.java @@ -0,0 +1,22 @@ +package com.novice.controller; + +import com.novice.domain.entity.User; +import com.novice.service.IUserService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("/user") +public class UserController { + @Resource + private IUserService iUserService; + + @GetMapping("/{userId}") + public User getUserById(@PathVariable("userId") Long userId) { + return iUserService.getById(userId); + } +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/domain/entity/User.java b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/domain/entity/User.java new file mode 100644 index 0000000000000000000000000000000000000000..a2ba69e6e4d7700d4beb64996c80ac15e74fbe46 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/domain/entity/User.java @@ -0,0 +1,30 @@ +package com.novice.domain.entity; + + +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("t_user") +public class User { + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "username") + private String username; + + @TableField(value = "age") + private Integer age; + + @TableField(value = "addr") + private String addr; +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/mapper/UserMapper.java b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/mapper/UserMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..613068da534bc1db8485c9d9f8a56d355b8ce868 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/mapper/UserMapper.java @@ -0,0 +1,7 @@ +package com.novice.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.novice.domain.entity.User; + +public interface UserMapper extends BaseMapper { +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/service/IUserService.java b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/service/IUserService.java new file mode 100644 index 0000000000000000000000000000000000000000..61ca201daefb8c9806cdc4bcd6505a7cf0de0a61 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/service/IUserService.java @@ -0,0 +1,7 @@ +package com.novice.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.novice.domain.entity.User; + +public interface IUserService extends IService { +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/service/impl/IUserServiceImpl.java b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/service/impl/IUserServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..71b9e5c597c502a18535c69dabeea0ca538c5258 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/java/com/novice/service/impl/IUserServiceImpl.java @@ -0,0 +1,13 @@ +package com.novice.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.novice.domain.entity.User; +import com.novice.mapper.UserMapper; +import com.novice.service.IUserService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(rollbackFor = Exception.class) +public class IUserServiceImpl extends ServiceImpl implements IUserService { +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/resources/application-druid.yml b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/resources/application-druid.yml new file mode 100644 index 0000000000000000000000000000000000000000..166c4885a73bf2d5579129704c3cc8b482518acc --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/resources/application-druid.yml @@ -0,0 +1,66 @@ +mybatis-plus: + # 搜索指定包别名 + type-aliases-package: com.novice.**.domain.entity + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapper-locations: classpath*:mapper/**/*Mapper.xml + configuration: + map-underscore-to-camel-case: true #自动驼峰映射 + +#日志配置 +logging: + level: + com.novice.mapper: debug + +spring: + # 数据源配置 + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/db-user?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: 123456 + + druid: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置连接超时时间 + connectTimeout: 30000 + # 配置网络超时时间 + socketTimeout: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: ruoyi + login-password: 123456 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true diff --git a/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/resources/application.yml b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..f279dc07b64350d765dc0e1730cebf7d2744818e --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-client-user/src/main/resources/application.yml @@ -0,0 +1,13 @@ +server: + port: 8301 + +spring: + profiles: + active: druid + application: + name: userservice + +eureka: + client: + service-url: + defaultZone: http://47.109.145.220:8300/eureka/ \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/eureka-server/pom.xml b/02-framework/cloud-demo/eureka-demo/eureka-server/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..1f63aa293aa1023f5abb6d279c8bfb06ed312e18 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-server/pom.xml @@ -0,0 +1,37 @@ + + + + eureka-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + eureka-server + + + 17 + 17 + + + + + cn.hutool + hutool-all + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + + + \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/eureka-server/src/main/java/com/novice/EurekaServerApp.java b/02-framework/cloud-demo/eureka-demo/eureka-server/src/main/java/com/novice/EurekaServerApp.java new file mode 100644 index 0000000000000000000000000000000000000000..47fd7f73ea9d4bb79327f59b80d6f2cff81a33b4 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-server/src/main/java/com/novice/EurekaServerApp.java @@ -0,0 +1,13 @@ +package com.novice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +@EnableEurekaServer +@SpringBootApplication +public class EurekaServerApp { + public static void main(String[] args) { + SpringApplication.run(EurekaServerApp.class, args); + } +} diff --git a/02-framework/cloud-demo/eureka-demo/eureka-server/src/main/resources/application.yml b/02-framework/cloud-demo/eureka-demo/eureka-server/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..626e445661696cbf7a5ea6fd369abdd138779286 --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/eureka-server/src/main/resources/application.yml @@ -0,0 +1,15 @@ +server: + port: 8300 + +spring: + application: + name: cloud-demo-eureka-server + +eureka: + instance: + hostname: localhost + client: + register-with-eureka: false + fetch-registry: false + service-url: + defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ \ No newline at end of file diff --git a/02-framework/cloud-demo/eureka-demo/pom.xml b/02-framework/cloud-demo/eureka-demo/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..c019e66f30a022b7ec26567d1893f36c9da2dfea --- /dev/null +++ b/02-framework/cloud-demo/eureka-demo/pom.xml @@ -0,0 +1,25 @@ + + + + cloud-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + eureka-demo + pom + + eureka-server + eureka-client-order + eureka-client-user + + + + 17 + 17 + + + \ No newline at end of file diff --git a/02-framework/cloud-demo/nacos-demo/assert/img.png b/02-framework/cloud-demo/nacos-demo/assert/img.png new file mode 100644 index 0000000000000000000000000000000000000000..79eff205405bc70f4ff08649c7d0fbb93878a04d Binary files /dev/null and b/02-framework/cloud-demo/nacos-demo/assert/img.png differ diff --git a/02-framework/cloud-demo/nacos-demo/assert/img_1.png b/02-framework/cloud-demo/nacos-demo/assert/img_1.png new file mode 100644 index 0000000000000000000000000000000000000000..f9e000d097140bc0eb838f28f9f93df3c4004cbd Binary files /dev/null and b/02-framework/cloud-demo/nacos-demo/assert/img_1.png differ diff --git a/02-framework/cloud-demo/nacos-demo/assert/img_2.png b/02-framework/cloud-demo/nacos-demo/assert/img_2.png new file mode 100644 index 0000000000000000000000000000000000000000..b66f26075a2ccb1f30e47a5ea6d8138e10ee0770 Binary files /dev/null and b/02-framework/cloud-demo/nacos-demo/assert/img_2.png differ diff --git a/02-framework/cloud-demo/nacos-demo/assert/img_3.png b/02-framework/cloud-demo/nacos-demo/assert/img_3.png new file mode 100644 index 0000000000000000000000000000000000000000..ab3fb0e198990519d30af0d24403f1e3651859e4 Binary files /dev/null and b/02-framework/cloud-demo/nacos-demo/assert/img_3.png differ diff --git a/02-framework/cloud-demo/nacos-demo/assert/img_4.png b/02-framework/cloud-demo/nacos-demo/assert/img_4.png new file mode 100644 index 0000000000000000000000000000000000000000..a938d0dd1f1ca265ab4ad17f272b52dfd9385a33 Binary files /dev/null and b/02-framework/cloud-demo/nacos-demo/assert/img_4.png differ diff --git a/02-framework/cloud-demo/nacos-demo/assert/img_5.png b/02-framework/cloud-demo/nacos-demo/assert/img_5.png new file mode 100644 index 0000000000000000000000000000000000000000..ac9d4253bd211de04d19ccfefc9b08880c0c8871 Binary files /dev/null and b/02-framework/cloud-demo/nacos-demo/assert/img_5.png differ diff --git a/02-framework/cloud-demo/nacos-demo/assert/nacos.md b/02-framework/cloud-demo/nacos-demo/assert/nacos.md new file mode 100644 index 0000000000000000000000000000000000000000..cd8502058be6ad0cbc411cdf650c8a88b4a91c52 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/assert/nacos.md @@ -0,0 +1,14 @@ +![img.png](img.png) +![img_1.png](img_1.png) +![img_2.png](img_2.png) +###3、openFeign优化 +- 使用连接池 +- 日志级别,不使用full,用none或basic +![img_3.png](img_3.png) +###4、gateway 过滤器 +![img_4.png](img_4.png) +- order值一样时执行顺序:defaultFilter > 路由过滤器 > GlobalFilter +- order值不一样时执行顺序:order值小的先执行 + +###5、gateway跨越处理 +![img_5.png](img_5.png) \ No newline at end of file diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/pom.xml b/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..683ac57e9e0452f62da0eb72606009ebb7b1149f --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/pom.xml @@ -0,0 +1,46 @@ + + + + nacos-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + nacos-client-gateway + + + 17 + 17 + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + + + + io.netty + netty-resolver-dns-native-macos + 4.1.72.Final + osx-aarch_64 + + + + + + \ No newline at end of file diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/java/com/novice/NacosGatewayApp.java b/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/java/com/novice/NacosGatewayApp.java new file mode 100644 index 0000000000000000000000000000000000000000..27e228f1bed5fcca3818f72af7d566f09274fb00 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/java/com/novice/NacosGatewayApp.java @@ -0,0 +1,14 @@ +package com.novice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + +@SpringBootApplication +@EnableDiscoveryClient +public class NacosGatewayApp { + public static void main(String[] args) + { + SpringApplication.run(NacosGatewayApp.class, args); + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/java/com/novice/config/AuthorizeFilter.java b/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/java/com/novice/config/AuthorizeFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..f63b95af217f63b3dd75bdf6e49fd8f842f47d17 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/java/com/novice/config/AuthorizeFilter.java @@ -0,0 +1,37 @@ +package com.novice.config; + + +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpCookie; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.util.MultiValueMap; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +@Order(-1) +@Component +public class AuthorizeFilter implements GlobalFilter { + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + // 1 获取请求参数 + ServerHttpRequest request = exchange.getRequest(); + MultiValueMap headers = request.getHeaders(); + // 2 获取请求头中的token + String token = headers.getFirst("Token"); + if(token == null || "".equals(token)){ + // a. token为空 + // b. token不为空,但token不正确 + System.out.println("token为空"); + exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); + return exchange.getResponse().setComplete(); + }else { + // token不为空,放行 + System.out.println("token不为空"); + return chain.filter(exchange); + } + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/resources/application.yml b/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..1b55f0a872c348b973e63544cce587c2f1c43671 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-gateway/src/main/resources/application.yml @@ -0,0 +1,45 @@ +server: + port: 10010 +spring: + application: + name: gateway + cloud: + nacos: + server-addr: http://47.109.145.220:8848 # nacos 服务地址 + discovery: + cluster-name: SH # 集群名称 + namespace: b660cd52-4526-434b-81f8-f177e351c5e9 + gateway: + globalcors: # 全局跨越处理配置 + add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题 + cors-configurations: + '[/**]': + allowed-origins: # 允许哪些网站的跨越请求 + - "http://localhost:8080" + - "http://127.0.0.1:8080" + - "http://192.168.1.100:8080" + - "*" + allowed-methods: # 允许哪些方法的跨越请求 + - "GET" + - "POST" + - "PUT" + - "DELETE" + - "OPTIONS" + - "*" + allowed-headers: "*" # 允许请求携带的请求头信息 + allow-credentials: true # 是否允许携带cookie + max-age: 360000 # 跨域请求的缓存时间 + discovery: + locator: + enabled: true + lower-case-service-id: true #小写服务名 + routes: # 网关路由配置 + - id: user-service # 路由标志,必须唯一 + uri: lb://userservice # 支持http和lb + predicates: # 路由匹配规则 + - Path=/api/user/** # 路由的匹配规则:以/user/开头的请求都匹配到这个路由 + - id: order-service + uri: lb://orderservice + predicates: + - Path=/api/order/** +# - RemoteAddr!=127.0.0.1 # 不允许127.0.0.1访问 \ No newline at end of file diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/pom.xml b/02-framework/cloud-demo/nacos-demo/nacos-client-order/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..a2df7285734248c63463f5e7a2a62976d97e7d45 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/pom.xml @@ -0,0 +1,85 @@ + + + + nacos-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + nacos-client-order + + + 17 + 17 + + + + cn.hutool + hutool-all + + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + + + + com.alibaba + druid-spring-boot-starter + + + + com.baomidou + mybatis-plus-boot-starter + + + + com.github.xiaoymin + knife4j-spring-boot-starter + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + io.github.openfeign + feign-httpclient + + + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix + + + + \ No newline at end of file diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/NacosOrderClientApp.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/NacosOrderClientApp.java new file mode 100644 index 0000000000000000000000000000000000000000..f262cdb7089221f9394051f2ab0da10733c558dd --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/NacosOrderClientApp.java @@ -0,0 +1,17 @@ +package com.novice; + +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.cloud.openfeign.EnableFeignClients; + +@EnableDiscoveryClient +@SpringBootApplication +@EnableFeignClients +@MapperScan(basePackages = "com.novice.mapper") +public class NacosOrderClientApp { + public static void main(String[] args) { + SpringApplication.run(NacosOrderClientApp.class, args); + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/config/Knife4jConfig.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/config/Knife4jConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..5342c9f759fa0e162e30eee4e462e951fb321461 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/config/Knife4jConfig.java @@ -0,0 +1,65 @@ +package com.novice.config; + +import com.alibaba.cloud.commons.lang.StringUtils; +import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.web.context.WebServerInitializedEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.net.Inet4Address; +import java.net.InetAddress; + +@Slf4j +@Configuration +@EnableSwagger2 +@EnableKnife4j +public class Knife4jConfig implements ApplicationListener { + private final static String PROJECT_NAME = "Nacos Demo===> 订单微服务"; // web浏览器tab标题 + private final static String PROJECT_VERSION = "V1.0"; + + @Bean + public Docket adminApiConfig() { + return new Docket(DocumentationType.SWAGGER_2) + .groupName("orderApi") + .apiInfo(adminApiInfo()) + .select() + // 指定@ApiOperation标注的接口被加入文档 + .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) +// .apis(RequestHandlerSelectors.basePackage("com.novice.**")) + .paths(PathSelectors.any()) + //只显示admin路径下的页面 +// .paths(PathSelectors.regex("/auth/.*")) + .build(); + } + + private ApiInfo adminApiInfo() { + return new ApiInfoBuilder() + .title(PROJECT_NAME + "-API文档") + .description("描述本系统提供的对外接口说明") + .version(PROJECT_VERSION) + .build(); + } + + @Override + public void onApplicationEvent(WebServerInitializedEvent event) { + try { + InetAddress inetAddress = Inet4Address.getLocalHost(); + String contextPath = event.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path"); + log.info("[" + PROJECT_NAME + "-项目启动成功!接口文档地址: http://" + + inetAddress.getHostAddress() + ":" + event.getWebServer().getPort() + + (StringUtils.isBlank(contextPath) ? "" : contextPath) + "/doc.html\033[0m"); + } catch (Exception e) { + log.error("接口文档搭建失败", e); + } + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/controller/OrderController.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/controller/OrderController.java new file mode 100644 index 0000000000000000000000000000000000000000..0c2590064ffcc5ea30cd5223afd80139c3700876 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/controller/OrderController.java @@ -0,0 +1,25 @@ +package com.novice.controller; + +import com.novice.domain.entity.Order; +import com.novice.service.IOrderService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@Api(tags = "订单服务") +@RestController +@RequestMapping("/api/order") +public class OrderController { + @Resource + private IOrderService orderService; + + @ApiOperation("根据id查询订单详情") + @RequestMapping("/{orderId}") + public Order getOrderById(@PathVariable("orderId") Long orderId) { + return orderService.getOrderById(orderId); + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/entity/Order.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/entity/Order.java new file mode 100644 index 0000000000000000000000000000000000000000..5d09ae9457c9db8c8603f0964b8a714324e4e41c --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/entity/Order.java @@ -0,0 +1,36 @@ +package com.novice.domain.entity; + +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 com.novice.domain.pojo.User; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName("t_order") +public class Order { + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "goods_name") + private String goodsName; + + @TableField(value = "count") + private Integer count; + + @TableField(value = "price") + private BigDecimal price; + + @TableField(value = "user_id") + private Long userId; + + @TableField(exist = false) + private User user; +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/pojo/User.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/pojo/User.java new file mode 100644 index 0000000000000000000000000000000000000000..454ab596e79dbc1059af4519bbe2771ddb83ad0e --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/pojo/User.java @@ -0,0 +1,30 @@ +package com.novice.domain.pojo; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class User { + private Long id; + + private String username; + + private Integer age; + + private String addr; + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", username='" + username + '\'' + + ", age=" + age + + ", addr='" + addr + '\'' + + '}'; + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/readme.md b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..8e4f42ba86747c7b8a6b31894b1514f10c3ae63d --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/domain/readme.md @@ -0,0 +1,4 @@ +pojo文件夹中:简单无规则Java对象,只有属性+get+set方法 +entity文件夹中是存放数据库实体对象类 +vo、params文件夹是存放请求入参数 +dto文件夹是存放请求返回参数 \ No newline at end of file diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/feignService/IUserServiceFeign.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/feignService/IUserServiceFeign.java new file mode 100644 index 0000000000000000000000000000000000000000..fa40b0410a3ec28cb9f6c554aa027f38baba7a97 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/feignService/IUserServiceFeign.java @@ -0,0 +1,19 @@ +package com.novice.feignService; + +import com.novice.domain.pojo.User; +import com.novice.feignService.fallback.UserServiceFallback; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +@FeignClient(name = "userservice", fallback = UserServiceFallback.class) +public interface IUserServiceFeign { + // 默认都是@RequestBody + /** + * 根据id查询用户 + * @param id id + * @return User + */ + @GetMapping("/api/user/{userId}") // 必须和服务提供者中的接口地址一致 + User getUserById(@PathVariable("userId") Long id); +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/feignService/fallback/UserServiceFallback.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/feignService/fallback/UserServiceFallback.java new file mode 100644 index 0000000000000000000000000000000000000000..0a4077579c39a255a94d60114dea6fc289902c36 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/feignService/fallback/UserServiceFallback.java @@ -0,0 +1,18 @@ +package com.novice.feignService.fallback; + +import com.novice.domain.pojo.User; +import com.novice.feignService.IUserServiceFeign; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +// Feign中的熔断与容错处理:如果远程服务无法返回数据,则将该重写的方法作为响应返回 +@Component +@Slf4j +public class UserServiceFallback implements IUserServiceFeign { + @Override + public User getUserById(Long id) { + // 当调用失败时,返回一个预定义的“备用”用户 + log.info("调用了熔断实现类,熔断返回信息-{}",id); + return new User(null,"备用用户", null,"无法获取真实用户信息"); + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/mapper/OrderMapper.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/mapper/OrderMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..4b30d403f8567447df028cda3c6c45bf72b837c1 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/mapper/OrderMapper.java @@ -0,0 +1,7 @@ +package com.novice.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.novice.domain.entity.Order; + +public interface OrderMapper extends BaseMapper { +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/service/IOrderService.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/service/IOrderService.java new file mode 100644 index 0000000000000000000000000000000000000000..8df4b04ee899f667e74a3cdfd337a7fe6cce95f3 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/service/IOrderService.java @@ -0,0 +1,8 @@ +package com.novice.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.novice.domain.entity.Order; + +public interface IOrderService extends IService { + Order getOrderById(Long orderId); +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/service/impl/IOrderServiceImpl.java b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/service/impl/IOrderServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..fbe0535cf9b19bc6404c9afcbb46c535c70533a2 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/java/com/novice/service/impl/IOrderServiceImpl.java @@ -0,0 +1,28 @@ +package com.novice.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.novice.domain.entity.Order; +import com.novice.domain.pojo.User; +import com.novice.feignService.IUserServiceFeign; +import com.novice.mapper.OrderMapper; +import com.novice.service.IOrderService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; + + +@Service +@Transactional(rollbackFor = Exception.class) +public class IOrderServiceImpl extends ServiceImpl implements IOrderService { + @Resource + private IUserServiceFeign iUserServiceFeign; + @Override + public Order getOrderById(Long orderId) { + Order order = baseMapper.selectById(orderId); + // 通过openFeign 声明式客户端调用userService + User user = iUserServiceFeign.getUserById(order.getUserId()); + order.setUser(user); + return order; + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/resources/application-druid.yml b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/resources/application-druid.yml new file mode 100644 index 0000000000000000000000000000000000000000..e393eb7eb36025d659dcf306c51dde5ff344ab21 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/resources/application-druid.yml @@ -0,0 +1,68 @@ +mybatis-plus: + # 搜索指定包别名 + type-aliases-package: com.novice.**.domain.entity + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapper-locations: classpath*:mapper/**/*Mapper.xml + configuration: + map-underscore-to-camel-case: true #自动驼峰映射 + +#日志配置 +logging: + level: + com.novice.mapper: debug + com.novice.feignService: debug + pattern: + dateformat: yyyy-MM-dd HH:mm:sss + +spring: + # 数据源配置 + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/db-order?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: 123456 + druid: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置连接超时时间 + connectTimeout: 30000 + # 配置网络超时时间 + socketTimeout: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: ruoyi + login-password: 123456 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/resources/application.yml b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..7588fa155dad3bf218c5cd452955511be1513736 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/resources/application.yml @@ -0,0 +1,29 @@ +server: + port: 9302 + +spring: + mvc: + pathmatch: + matching-strategy: ant_path_matcher + profiles: + active: druid + application: + name: orderservice + cloud: + nacos: + server-addr: http://47.109.145.220:8848 # nacos 服务地址 + discovery: + cluster-name: SH # 集群名称 + namespace: b660cd52-4526-434b-81f8-f177e351c5e9 + +feign: + circuitbreaker: + enabled: true # 开启熔断器 + client: + config: + default: + loggerLevel: basic + httpclient: + enabled: true # 开启feign对httpClient的支持(通过线程池的方式对feign进行优化) + max-connections: 200 # 最大连接数 + max-connections-per-route: 50 # 每个路径的最大连接数 diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/resources/bootstrap.yml b/02-framework/cloud-demo/nacos-demo/nacos-client-order/src/main/resources/bootstrap.yml new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/pom.xml b/02-framework/cloud-demo/nacos-demo/nacos-client-user/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..0268360246f35e3ab321ded5bc8086e61e4851c9 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/pom.xml @@ -0,0 +1,82 @@ + + + + nacos-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + nacos-client-user + + + 17 + 17 + + + + cn.hutool + hutool-all + + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + + + + com.alibaba + druid-spring-boot-starter + + + + com.baomidou + mybatis-plus-boot-starter + + + + com.github.xiaoymin + knife4j-spring-boot-starter + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + + io.github.openfeign + feign-httpclient + + + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix + + + + \ No newline at end of file diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/NacosUserClientApp.java b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/NacosUserClientApp.java new file mode 100644 index 0000000000000000000000000000000000000000..2da8d5efc8109711d5a42dd8571d042f09620188 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/NacosUserClientApp.java @@ -0,0 +1,18 @@ +package com.novice; + +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.cloud.openfeign.EnableFeignClients; + +@SpringBootApplication +@EnableDiscoveryClient // 服务注册和发现 +@EnableFeignClients // 开启openfeign +@MapperScan(basePackages = "com.novice.mapper") +public class NacosUserClientApp { + public static void main(String[] args) + { + SpringApplication.run(NacosUserClientApp.class,args); + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/controller/UserController.java b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/controller/UserController.java new file mode 100644 index 0000000000000000000000000000000000000000..8a3d7cd7384395317944b179faafb6ab2d6a5f9f --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/controller/UserController.java @@ -0,0 +1,22 @@ +package com.novice.controller; + +import com.novice.domain.entity.User; +import com.novice.service.IUserService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("/api/user") +public class UserController { + @Resource + private IUserService iUserService; + + @GetMapping("/{userId}") + public User getUserById(@PathVariable("userId") Long userId) { + return iUserService.getById(userId); + } +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/domain/entity/User.java b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/domain/entity/User.java new file mode 100644 index 0000000000000000000000000000000000000000..a2ba69e6e4d7700d4beb64996c80ac15e74fbe46 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/domain/entity/User.java @@ -0,0 +1,30 @@ +package com.novice.domain.entity; + + +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("t_user") +public class User { + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "username") + private String username; + + @TableField(value = "age") + private Integer age; + + @TableField(value = "addr") + private String addr; +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/mapper/UserMapper.java b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/mapper/UserMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..613068da534bc1db8485c9d9f8a56d355b8ce868 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/mapper/UserMapper.java @@ -0,0 +1,7 @@ +package com.novice.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.novice.domain.entity.User; + +public interface UserMapper extends BaseMapper { +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/service/IUserService.java b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/service/IUserService.java new file mode 100644 index 0000000000000000000000000000000000000000..61ca201daefb8c9806cdc4bcd6505a7cf0de0a61 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/service/IUserService.java @@ -0,0 +1,7 @@ +package com.novice.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.novice.domain.entity.User; + +public interface IUserService extends IService { +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/service/impl/IUserServiceImpl.java b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/service/impl/IUserServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..71b9e5c597c502a18535c69dabeea0ca538c5258 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/java/com/novice/service/impl/IUserServiceImpl.java @@ -0,0 +1,13 @@ +package com.novice.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.novice.domain.entity.User; +import com.novice.mapper.UserMapper; +import com.novice.service.IUserService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(rollbackFor = Exception.class) +public class IUserServiceImpl extends ServiceImpl implements IUserService { +} diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/resources/application-druid.yml b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/resources/application-druid.yml new file mode 100644 index 0000000000000000000000000000000000000000..09615554e6450a0c31c2188d7110a1a54105972b --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/resources/application-druid.yml @@ -0,0 +1,67 @@ +mybatis-plus: + # 搜索指定包别名 + type-aliases-package: com.novice.**.domain.entity + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapper-locations: classpath*:mapper/**/*Mapper.xml + configuration: + map-underscore-to-camel-case: true #自动驼峰映射 + +#日志配置 +logging: + level: + com.novice.mapper: debug + + +spring: + # 数据源配置 + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/db-user?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: 123456 + + druid: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置连接超时时间 + connectTimeout: 30000 + # 配置网络超时时间 + socketTimeout: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: ruoyi + login-password: 123456 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true diff --git a/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/resources/application.yml b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..49cd932c29d5f3c61ef8acf012391dcf32338035 --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/nacos-client-user/src/main/resources/application.yml @@ -0,0 +1,17 @@ +server: + port: 9304 + +spring: + mvc: + pathmatch: + matching-strategy: ant_path_matcher + profiles: + active: druid + application: + name: userservice + cloud: + nacos: + server-addr: http://47.109.145.220:8848 # nacos 服务地址 + discovery: + cluster-name: SH # 集群名称 + namespace: b660cd52-4526-434b-81f8-f177e351c5e9 \ No newline at end of file diff --git a/02-framework/cloud-demo/nacos-demo/pom.xml b/02-framework/cloud-demo/nacos-demo/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..ab44a6c686723549296b9cea6a1106cc6b45267d --- /dev/null +++ b/02-framework/cloud-demo/nacos-demo/pom.xml @@ -0,0 +1,24 @@ + + + + cloud-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + nacos-demo + pom + + nacos-client-user + nacos-client-order + nacos-client-gateway + + + + 17 + 17 + + \ No newline at end of file diff --git a/02-framework/cloud-demo/pom.xml b/02-framework/cloud-demo/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..5fcde42ff1e2aafee23bd1abf10199a9de0c6155 --- /dev/null +++ b/02-framework/cloud-demo/pom.xml @@ -0,0 +1,29 @@ + + + + 02-framework + org.example + 1.0-SNAPSHOT + + 4.0.0 + + cloud-demo + pom + + eureka-demo + nacos-demo + + + + 17 + 17 + + + + org.projectlombok + lombok + + + \ No newline at end of file diff --git a/02-framework/elasticsearch-demo/pom.xml b/02-framework/elasticsearch-demo/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..e5ae6b6b4fea27242a466904ef9952856f095bde --- /dev/null +++ b/02-framework/elasticsearch-demo/pom.xml @@ -0,0 +1,53 @@ + + + + 02-framework + org.example + 1.0-SNAPSHOT + + 4.0.0 + + elasticsearch-demo + + + 17 + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + + + org.elasticsearch.client + elasticsearch-rest-high-level-client + + + com.alibaba + fastjson + + + mysql + mysql-connector-java + + + com.alibaba + druid-spring-boot-starter + + + com.baomidou + mybatis-plus-boot-starter + + + org.projectlombok + lombok + + + + \ No newline at end of file diff --git a/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/ElkApplication.java b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/ElkApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..1f057ce3e2d88938668decc8043abebd954338c3 --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/ElkApplication.java @@ -0,0 +1,13 @@ +package com.novice.elasticsearch; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@MapperScan(basePackages = "com.novice.elasticsearch.mapper") +public class ElkApplication { + public static void main(String[] args) { + SpringApplication.run(ElkApplication.class, args); + } +} diff --git a/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/constant/HotelConstants.java b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/constant/HotelConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..e22bd88c04d5794eda696ae4f515f575462f0fea --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/constant/HotelConstants.java @@ -0,0 +1,64 @@ +package com.novice.elasticsearch.constant; + +public class HotelConstants { + public static final String MAPPING_TEMPLATE = "{\n" + + " \"mappings\": {\n" + + " \"properties\": {\n" + + " \"id\":{\n" + + " \"type\": \"keyword\",\n" + + " \"index\": true\n" + + " },\n" + + " \"name\":{\n" + + " \"type\": \"text\",\n" + + " \"analyzer\": \"ik_max_word\", \n" + + " \"index\": true,\n" + + " \"copy_to\": \"all\"\n" + + " },\n" + + " \"address\":{\n" + + " \"type\": \"text\",\n" + + " \"analyzer\": \"ik_smart\", \n" + + " \"index\": true\n" + + " },\n" + + " \"price\":{\n" + + " \"type\": \"integer\",\n" + + " \"index\": true\n" + + " },\n" + + " \"score\":{\n" + + " \"type\": \"integer\",\n" + + " \"index\": true\n" + + " },\n" + + " \"brand\":{\n" + + " \"type\": \"keyword\",\n" + + " \"index\": true,\n" + + " \"copy_to\": \"all\"\n" + + " },\n" + + " \"city\":{\n" + + " \"type\": \"keyword\",\n" + + " \"index\": true\n" + + " },\n" + + " \"starName\":{\n" + + " \"type\": \"keyword\",\n" + + " \"index\": true\n" + + " },\n" + + " \"business\":{\n" + + " \"type\": \"keyword\",\n" + + " \"index\": true,\n" + + " \"copy_to\": \"all\"\n" + + " },\n" + + " \"latitude\":{\n" + + " \"type\": \"geo_point\",\n" + + " \"index\": false\n" + + " },\n" + + " \"pic\":{\n" + + " \"type\": \"keyword\",\n" + + " \"index\": false\n" + + " },\n" + + " \"all\":{\n" + + " \"type\": \"text\",\n" + + " \"analyzer\": \"ik_max_word\", \n" + + " \"index\": true\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; +} diff --git a/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/controller/HotelController.java b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/controller/HotelController.java new file mode 100644 index 0000000000000000000000000000000000000000..43d01774c16eac1eef55e63fe1756e9966cebeaa --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/controller/HotelController.java @@ -0,0 +1,20 @@ +package com.novice.elasticsearch.controller; + +import com.novice.elasticsearch.domain.entity.Hotel; +import com.novice.elasticsearch.service.IHotelService; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("/hotel") +public class HotelController { + @Resource + private IHotelService hotelService; + @RequestMapping("/index") + public Hotel index() { + Hotel hotel = hotelService.getById(36934L); + return hotel; + } +} diff --git a/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/domain/doc/HotelDoc.java b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/domain/doc/HotelDoc.java new file mode 100644 index 0000000000000000000000000000000000000000..594a998cacb6aa811ca7532b2d913aa7e25070ff --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/domain/doc/HotelDoc.java @@ -0,0 +1,37 @@ +package com.novice.elasticsearch.domain.doc; + +import com.novice.elasticsearch.domain.entity.Hotel; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +public class HotelDoc { + private Long id; + private String name; + private String address; + private Integer price; + private Integer score; + private String brand; + private String city; + private String starName; + private String business; + private String location; + private String pic; + + public HotelDoc(Hotel hotel) { + this.id = hotel.getId(); + this.name = hotel.getName(); + this.address = hotel.getAddress(); + this.price = hotel.getPrice(); + this.score = hotel.getScore(); + this.brand = hotel.getBrand(); + this.city = hotel.getCity(); + this.starName = hotel.getStarName(); + this.business = hotel.getBusiness(); + this.location = hotel.getLatitude() + ", " + hotel.getLongitude(); + this.pic = hotel.getPic(); + } +} + + diff --git a/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/domain/entity/Hotel.java b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/domain/entity/Hotel.java new file mode 100644 index 0000000000000000000000000000000000000000..68c3d87caa51768e09505563d87f036d14d5e4eb --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/domain/entity/Hotel.java @@ -0,0 +1,25 @@ +package com.novice.elasticsearch.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +@Data +@TableName("tb_hotel") +public class Hotel { + @TableId(type = IdType.INPUT) //主键 + private Long id; + private String name; + private String address; + private Integer price; + private Integer score; + private String brand; + private String city; + private String starName; + private String business; + private String longitude; + private String latitude; + private String pic; +} + diff --git a/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/mapper/HotelMapper.java b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/mapper/HotelMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..60c09304a14409dd5adaadb58328ae0f09985388 --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/mapper/HotelMapper.java @@ -0,0 +1,7 @@ +package com.novice.elasticsearch.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.novice.elasticsearch.domain.entity.Hotel; + +public interface HotelMapper extends BaseMapper { +} diff --git a/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/service/IHotelService.java b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/service/IHotelService.java new file mode 100644 index 0000000000000000000000000000000000000000..c3bcf0f1a2d68fec3078cfecadbabe975df3c184 --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/service/IHotelService.java @@ -0,0 +1,7 @@ +package com.novice.elasticsearch.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.novice.elasticsearch.domain.entity.Hotel; + +public interface IHotelService extends IService { +} diff --git a/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/service/impl/IHotelServiceImpl.java b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/service/impl/IHotelServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..4d76e003037f43b785e0d8746e26b6626bab9fc0 --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/java/com/novice/elasticsearch/service/impl/IHotelServiceImpl.java @@ -0,0 +1,13 @@ +package com.novice.elasticsearch.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.novice.elasticsearch.domain.entity.Hotel; +import com.novice.elasticsearch.mapper.HotelMapper; +import com.novice.elasticsearch.service.IHotelService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(rollbackFor = Exception.class) +public class IHotelServiceImpl extends ServiceImpl implements IHotelService { +} diff --git a/02-framework/elasticsearch-demo/src/main/resources/application-druid.yml b/02-framework/elasticsearch-demo/src/main/resources/application-druid.yml new file mode 100644 index 0000000000000000000000000000000000000000..719f209d059e054f82d93f3d538748025e0f8c88 --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/resources/application-druid.yml @@ -0,0 +1,53 @@ +spring: + # 数据源配置 + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/demo-elasticsearch?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: 123456 + + druid: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置连接超时时间 + connectTimeout: 30000 + # 配置网络超时时间 + socketTimeout: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: ruoyi + login-password: 123456 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true diff --git a/02-framework/elasticsearch-demo/src/main/resources/application.yml b/02-framework/elasticsearch-demo/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..1623257006dae857f6567a674302342f53f6729d --- /dev/null +++ b/02-framework/elasticsearch-demo/src/main/resources/application.yml @@ -0,0 +1,19 @@ +server: + port: 8301 + +spring: + profiles: + active: druid + +mybatis-plus: + # 搜索指定包别名 + type-aliases-package: com.novice.**.domain.entity + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapper-locations: classpath*:mapper/**/*Mapper.xml + configuration: + map-underscore-to-camel-case: true #自动驼峰映射 + +#日志配置 +logging: + level: + com.novice.mapper: debug \ No newline at end of file diff --git a/02-framework/elasticsearch-demo/src/test/java/com/novice/elasticsearch/DSLQueryTest.java b/02-framework/elasticsearch-demo/src/test/java/com/novice/elasticsearch/DSLQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..17bf3450880f536fe27cef1ed234adfbf6724954 --- /dev/null +++ b/02-framework/elasticsearch-demo/src/test/java/com/novice/elasticsearch/DSLQueryTest.java @@ -0,0 +1,70 @@ +package com.novice.elasticsearch; + +import com.novice.elasticsearch.service.IHotelService; +import org.apache.http.HttpHost; +import org.elasticsearch.action.get.GetRequest; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestHighLevelClient; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.io.IOException; + +@SpringBootTest +public class DSLQueryTest { + @Autowired + private IHotelService hotelService; + + private RestHighLevelClient client; + + @BeforeEach + void setUp() { + this.client = new RestHighLevelClient(RestClient.builder( + HttpHost.create("http://47.109.145.220:9200") + )); + } + + @AfterEach + void tearDown() throws IOException { + this.client.close(); + } + + // DSL查询语法 + // 查询所有 + public void queryAll() throws IOException { + String query = "{\n" + + " \"query\": {\n" + + " \"match_all\": {}\n" + + " }\n" + + "}"; + GetRequest getRequest = new GetRequest(); + } + + // 全文检索搜索 常用于搜索框搜索 + + /** + *

+ * Get /indexName/_search + * { + * "query": { + * "match": { + * "all": "酒店" + * } + * } + * } + *

+ * @throws IOException + */ + public void queryByMatch() throws IOException { + String query = "{\n" + + " \"query\": {\n" + + " \"match\": {\n" + + " \"all\": \"酒店\"\n" + + " }\n" + + " }\n" + + "}"; + GetRequest getRequest = new GetRequest(); + } +} diff --git a/02-framework/elasticsearch-demo/src/test/java/com/novice/elasticsearch/ElkApplicationTest.java b/02-framework/elasticsearch-demo/src/test/java/com/novice/elasticsearch/ElkApplicationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..764d81222687f6dbc749a9479bea0e2ace4675bd --- /dev/null +++ b/02-framework/elasticsearch-demo/src/test/java/com/novice/elasticsearch/ElkApplicationTest.java @@ -0,0 +1,172 @@ +package com.novice.elasticsearch; + +import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.databind.util.JSONPObject; +import com.novice.elasticsearch.constant.HotelConstants; +import com.novice.elasticsearch.domain.doc.HotelDoc; +import com.novice.elasticsearch.domain.entity.Hotel; +import com.novice.elasticsearch.service.IHotelService; +import org.apache.http.HttpHost; +import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; +import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; +import org.elasticsearch.action.bulk.BulkRequest; +import org.elasticsearch.action.delete.DeleteRequest; +import org.elasticsearch.action.delete.DeleteResponse; +import org.elasticsearch.action.get.GetRequest; +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.update.UpdateRequest; +import org.elasticsearch.action.update.UpdateResponse; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.client.indices.GetIndexRequest; +import org.elasticsearch.common.xcontent.XContentType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.io.IOException; +import java.util.List; + +@SpringBootTest +public class ElkApplicationTest { + @Autowired + private IHotelService hotelService; + + private RestHighLevelClient client; + + @BeforeEach + void setUp() { + this.client = new RestHighLevelClient(RestClient.builder( + HttpHost.create("http://47.109.145.220:9200") + )); + } + + @AfterEach + void tearDown() throws IOException { + this.client.close(); + } + + // 测试连接 + @Test + void testInit() { + System.out.println(this.client); + } + + // 测试创建索引(理解为DB中的表) + @Test + void testCreateIndex() throws IOException { + // 1.准备Request对象 + IndexRequest request = new IndexRequest("hotel"); + // 2.准备请求参数,DSL文档 + request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON); + // 3.发送请求 + IndexResponse index = client.index(request, RequestOptions.DEFAULT); + System.out.println("index = " + index); + } + + // 判断索引库是否存在 + @Test + void testExistsHotelIndex() throws IOException { + // 1.创建Request对象 + GetIndexRequest request = new GetIndexRequest("hotel"); + // 2.发送请求 + boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); + System.out.println("exists = " + exists); + } + + // 删除索引库 + @Test + void testDeleteHotelIndex() throws IOException { + // 1.创建Request对象 + DeleteIndexRequest request = new DeleteIndexRequest("hotel"); + // 2.发送请求 + client.indices().delete(request, RequestOptions.DEFAULT); + } + + // 测试倒排索引到ES中,单个循环 + @Test + void testAddDocumentToEs() throws IOException { + List hotels = hotelService.list(null); + + hotels.forEach(item -> { + try { + // 1.转换为文档类型 + HotelDoc hotelDoc = new HotelDoc(item); + // 2.将HotelDoc转json + String hotelJson = JSON.toJSONString(hotelDoc); + // 3.准备Request对象 + IndexRequest request = new IndexRequest("hotel").id(item.getId().toString()); + // 4.准备Json文档 + request.source(hotelJson, XContentType.JSON); + // 5.发送请求 + client.index(request, RequestOptions.DEFAULT); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + + // 测试倒排索引到ES中,批量 + @Test + void testAddDocumentToEsBatch() throws IOException { + List hotels = hotelService.list(null); + BulkRequest bulkRequest = new BulkRequest(); + hotels.forEach(item -> { + // 1.转换为文档类型 + HotelDoc hotelDoc = new HotelDoc(item); + // 2.将HotelDoc转json + String hotelDocJson = JSON.toJSONString(hotelDoc); + // 3.准备Request对象 + IndexRequest request = new IndexRequest("hotel").id(item.getId().toString()); + // 4.准备Json文档 + request.source(hotelDocJson, XContentType.JSON); + bulkRequest.add(request); + }); + // 5.发送请求 + client.bulk(bulkRequest, RequestOptions.DEFAULT); + } + + // 测试获取文档 + @Test + void testGetDocumentById() throws IOException { + // 1.准备Request对象 + GetRequest request = new GetRequest("hotel", "61083"); + // 2.发送请求,等到响应 + GetResponse response = client.get(request, RequestOptions.DEFAULT); + // 3.解析响应 + String docJsonStr = response.getSourceAsString(); + HotelDoc hotelDoc = JSON.parseObject(docJsonStr, HotelDoc.class); + System.out.println("hotelDoc = " + hotelDoc); + } + + // 根据id修改文档 + // 全量更新(删除以前的数据插入新的数据) + // 局部更新 + @Test + void testUpdateDocumentById() throws IOException { + // 1.准备Request对象 + UpdateRequest request = new UpdateRequest("hotel", "61083"); + // 2.准备请求参数 + request.doc( + "price", "999", + "starName", "四钻" + ); + // 3.发送请求,等到响应 + UpdateResponse response = client.update(request, RequestOptions.DEFAULT); + } + + // 测试删除文档 + @Test + void testDeleteDocumentById() throws IOException { + // 1.准备Request对象 + DeleteRequest request = new DeleteRequest("hotel", "61083"); + // 2.发送请求,等到响应 + DeleteResponse response = client.delete(request, RequestOptions.DEFAULT); + } + +} \ No newline at end of file diff --git a/02-framework/pom.xml b/02-framework/pom.xml index ab417ec61cfb43b62d4e385de5b81ddd3c7ad837..bde72391fbfba25dc7fbc64913c7ae76f0f341cb 100644 --- a/02-framework/pom.xml +++ b/02-framework/pom.xml @@ -6,11 +6,145 @@ org.example 02-framework + pom 1.0-SNAPSHOT + + cloud-demo + rabbitmq-demo + elasticsearch-demo + 17 17 + + 2.6.3 + 2021.0.1 + 2021.0.1.0 + 2.2.10.RELEASE + 3.5.2 + 8.0.31 + 1.2.14 + 2.6.13 + 3.0.3 + 5.8.0.M1 + 1.18.28 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix + ${spring-cloud-netflix.version} + + + + mysql + mysql-connector-java + ${mysql.version} + + + + com.alibaba + druid-spring-boot-starter + ${druid.version} + + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.version} + + + + org.springframework.boot + spring-boot-starter-data-redis + ${redis.version} + + + + com.github.xiaoymin + knife4j-spring-boot-starter + ${knife4j.version} + + + + cn.hutool + hutool-all + ${hutool.version} + + + + org.projectlombok + lombok + ${lombok.version} + + + com.alibaba + fastjson + 2.0.21 + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + UTF-8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + com.example.demo.DemoApplication + true + + + + repackage + + repackage + + + + + + \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/01-simple-queue/consumer/pom.xml b/02-framework/rabbitmq-demo/01-simple-queue/consumer/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..a401deecc6cd2a0fb37024197dfb61a820bafb4b --- /dev/null +++ b/02-framework/rabbitmq-demo/01-simple-queue/consumer/pom.xml @@ -0,0 +1,25 @@ + + + + 01-simple-queue + org.example + 1.0-SNAPSHOT + + 4.0.0 + + consumer + + + 17 + 17 + + + + org.springframework.boot + spring-boot-starter-amqp + + + + \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/01-simple-queue/consumer/src/main/java/com/novice/mq/helloworld/ConsumerTest.java b/02-framework/rabbitmq-demo/01-simple-queue/consumer/src/main/java/com/novice/mq/helloworld/ConsumerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..03c7e9784b0ef6c694a90d9d657c4e075607e088 --- /dev/null +++ b/02-framework/rabbitmq-demo/01-simple-queue/consumer/src/main/java/com/novice/mq/helloworld/ConsumerTest.java @@ -0,0 +1,36 @@ +package com.novice.mq.helloworld; + +import com.rabbitmq.client.*; + +import java.io.IOException; +import java.util.concurrent.TimeoutException; + +public class ConsumerTest { + public static void main(String[] args) throws IOException, TimeoutException { + //1、创建连接工厂 + ConnectionFactory connectionFactory = new ConnectionFactory(); + //1-1、设置连接工厂的参数 + connectionFactory.setHost("47.109.145.220"); + connectionFactory.setPort(5672); + connectionFactory.setVirtualHost("/"); + connectionFactory.setUsername("itcast"); + connectionFactory.setPassword("123321"); + //1-2、通过连接工厂创建连接 + Connection connection = connectionFactory.newConnection(); + //2、通过连接创建通道 + Channel channel = connection.createChannel(); + //3、创建队列 + String queueName = "simple.queue"; + channel.queueDeclare(queueName, false, false, false, null); + //4、订阅消息队列 + channel.basicConsume(queueName,true,new DefaultConsumer(channel){ + @Override + public void handleDelivery(String consumerTag, Envelope envelope, + AMQP.BasicProperties properties, byte[] body) throws IOException { + // 5、处理消息 + String msg = new String(body); + System.out.println("消费者收到消息:" + msg); + } + }); + } +} diff --git a/02-framework/rabbitmq-demo/01-simple-queue/pom.xml b/02-framework/rabbitmq-demo/01-simple-queue/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..961ab20cd51db868954d8ccf8655d9e01e7f7b9e --- /dev/null +++ b/02-framework/rabbitmq-demo/01-simple-queue/pom.xml @@ -0,0 +1,24 @@ + + + + rabbitmq-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + 01-simple-queue + pom + + publisher + consumer + + + + 17 + 17 + + + \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/01-simple-queue/publisher/pom.xml b/02-framework/rabbitmq-demo/01-simple-queue/publisher/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..8488258a1831a39ac8cbd81eb4fff8cc34e2f482 --- /dev/null +++ b/02-framework/rabbitmq-demo/01-simple-queue/publisher/pom.xml @@ -0,0 +1,19 @@ + + + + 01-simple-queue + org.example + 1.0-SNAPSHOT + + 4.0.0 + + publisher + + + 17 + 17 + + + \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/01-simple-queue/publisher/src/main/java/com/novice/mq/helloworld/PublisherTest.java b/02-framework/rabbitmq-demo/01-simple-queue/publisher/src/main/java/com/novice/mq/helloworld/PublisherTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0a3973cfff92609cccb435b10a0b0654ab3c9884 --- /dev/null +++ b/02-framework/rabbitmq-demo/01-simple-queue/publisher/src/main/java/com/novice/mq/helloworld/PublisherTest.java @@ -0,0 +1,36 @@ +package com.novice.mq.helloworld; + +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; + +import java.io.IOException; +import java.util.concurrent.TimeoutException; + +public class PublisherTest { + public static void main(String[] args)throws IOException, TimeoutException { + //1、创建连接工厂 + ConnectionFactory connectionFactory = new ConnectionFactory(); + //1-1、设置连接工厂的参数 + connectionFactory.setHost("47.109.145.220"); + connectionFactory.setPort(5672); + connectionFactory.setVirtualHost("/"); + connectionFactory.setUsername("itcast"); + connectionFactory.setPassword("123321"); + //1-2、通过连接工厂创建连接 + Connection connection = connectionFactory.newConnection(); + //2、通过连接创建通道 + Channel channel = connection.createChannel(); + //3、创建队列 + String queueName = "simple.queue"; + channel.queueDeclare(queueName, false, false, false, null); + //4、发布消息 + String msg = "hello rabbitMQ!fjlaksfjlasdkjflakdjflaskdjflasdkjflakdjflsjdlskjfla"; + channel.basicPublish("", queueName, null, msg.getBytes()); + System.out.println("消息发送成功!"); + // 5、关闭通道和连接 + channel.close(); + connection.close(); + + } +} diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/pom.xml b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..3882bcfa0d4f39b69774eff8fb40cce9809524cc --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/pom.xml @@ -0,0 +1,19 @@ + + + + 02-springAMQP + org.example + 1.0-SNAPSHOT + + 4.0.0 + + AMQPConsumer + + + 17 + 17 + + + \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/ConsumerApplication.java b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/ConsumerApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..3be89260dd1271e964db3dc228cf54753b7418d8 --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/ConsumerApplication.java @@ -0,0 +1,11 @@ +package com.novice.mq; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ConsumerApplication { + public static void main(String[] args) { + SpringApplication.run(ConsumerApplication.class, args); + } +} diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/config/FanoutConfig.java b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/config/FanoutConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..df6daba28dbd283632b8d625224e5b47a97b3405 --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/config/FanoutConfig.java @@ -0,0 +1,40 @@ +package com.novice.mq.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.FanoutExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class FanoutConfig { + public static final String EXCHANGE_FANOUT_NAME = "exchange_fanout"; + public static final String QUEUE_FANOUT_NAME1 = "fanout.queue1"; + public static final String QUEUE_FANOUT_NAME2 = "fanout.queue2"; + + @Bean + public FanoutExchange fanoutExchange() { + return new FanoutExchange(EXCHANGE_FANOUT_NAME); + } + @Bean + public Queue queue1() { + return new Queue(QUEUE_FANOUT_NAME1); + } + + // 交换机和队列进行绑定 + @Bean + public Binding fanoutBindQueue1(FanoutExchange fanoutExchange, Queue queue1) { + return BindingBuilder.bind(queue1).to(fanoutExchange); + } + + // ========================= + @Bean + public Queue queue2() { + return new Queue(QUEUE_FANOUT_NAME2); + } + @Bean + public Binding fanoutBindQueue2(FanoutExchange fanoutExchange, Queue queue2) { + return BindingBuilder.bind(queue2).to(fanoutExchange); + } +} diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/listener/SpringRabbitListener.java b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/listener/SpringRabbitListener.java new file mode 100644 index 0000000000000000000000000000000000000000..8a63d97cbc80f56cd3b40c619b4d3708296eb381 --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/java/com/novice/mq/listener/SpringRabbitListener.java @@ -0,0 +1,95 @@ +package com.novice.mq.listener; + +import org.springframework.amqp.core.ExchangeTypes; +import org.springframework.amqp.rabbit.annotation.Exchange; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.QueueBinding; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +import java.time.LocalTime; + +@Component +public class SpringRabbitListener { + // 1、简单队列模式 + @RabbitListener(queues = "simple.queue") + public void listenSimpleQueue(String message) { + System.out.println("接收到simple.queue消息:" + message); + } + + + // 提高消息处理进度,避免消息堆积 + // 2、工作队列模式-1[需要进行消息预取] + @RabbitListener(queues = "work.queue") + public void listenWorkQueue1(String message) throws InterruptedException { + System.out.println("1----接收到work.queue消息:" + message + LocalTime.now()); + Thread.sleep(20); + } + + // 2、工作队列模式-2[需要进行消息预取] + @RabbitListener(queues = "work.queue") + public void listenWorkQueue2(String message) throws InterruptedException { + System.err.println("2---------------接收到work.queue消息:" + message + LocalTime.now()); + Thread.sleep(200); + } + + // 3、发布订阅模式--》fanout交换机 + @RabbitListener(queues = "fanout.queue1") + public void listenFanoutQueue1(String message) throws InterruptedException { + System.out.println("1---------------接收到fanout.queue1消息:" + message + LocalTime.now()); + Thread.sleep(200); + } + @RabbitListener(queues = "fanout.queue2") + public void listenFanoutQueue2(String message) throws InterruptedException { + System.out.println("2---------------接收到fanout.queue2消息:" + message + LocalTime.now()); + Thread.sleep(200); + } + + static final String EXCHANGE_DIRECT_NAME = "exchange_direct"; + static final String DIRECT_QUEUE_1 = "direct.queue1"; + static final String DIRECT_QUEUE_2 = "direct.queue2"; + + // 3、发布订阅模式--》direct交换机 + @RabbitListener(bindings = @QueueBinding( + value = @Queue(name = DIRECT_QUEUE_1), + exchange = @Exchange(value = EXCHANGE_DIRECT_NAME, type = ExchangeTypes.DIRECT), + key = {"blue","red"} + )) + public void listenDirectQueue1(String message) throws InterruptedException { + System.out.println("1-------接收到direct.queue1消息:" + message + LocalTime.now()); + } + @RabbitListener(bindings = @QueueBinding( + value = @Queue(name = DIRECT_QUEUE_2), + exchange = @Exchange(value = EXCHANGE_DIRECT_NAME, type = ExchangeTypes.DIRECT), + key = {"red","yellow"} + )) + public void listenDirectQueue2(String message) throws InterruptedException { + System.out.println("2---------------接收到direct.queue2消息:" + message + LocalTime.now()); + } + + // 3、发布订阅模式--》topic交换机 + static final String EXCHANGE_TOPIC_NAME = "exchange_topic"; + static final String TOPIC_QUEUE_1 = "topic.queue1"; + static final String TOPIC_QUEUE_2 = "topic.queue2"; + /** + * # 表示任意通配符 + * . 表示一个通配符 + * @param message 消息 + */ + @RabbitListener(bindings = @QueueBinding( + value = @Queue(name = TOPIC_QUEUE_1), + exchange = @Exchange(value = EXCHANGE_TOPIC_NAME, type = ExchangeTypes.TOPIC), + key = "china.#" + )) + public void listenTopicQueue(String message) { + System.out.println("2--------接收到topic.queue1消息:" + message + LocalTime.now()); + } + @RabbitListener(bindings = @QueueBinding( + value = @Queue(name = TOPIC_QUEUE_2), + exchange = @Exchange(value = EXCHANGE_TOPIC_NAME, type = ExchangeTypes.TOPIC), + key = "#.news" + )) + public void listenTopicQueue2(String message) { + System.out.println("2---------------接收到topic.queue2消息:" + message + LocalTime.now()); + } +} \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/resources/application.yml b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..2f5a979c2b48d67b75666b133e2f822721a9462b --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPConsumer/src/main/resources/application.yml @@ -0,0 +1,13 @@ +logging: + pattern: + dateformat: yyyy-MM-dd HH:mm:ss +spring: + rabbitmq: + host: 47.109.145.220 # rabbitmq IP地址 + port: 5672 + username: itcast + password: 123321 + virtual-host: / + listener: + simple: + prefetch: 1 # 消息队列中,一个消费者每次读取的消息条数 diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/pom.xml b/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..28522bf0cf2f583fbcc8a0435146456e6954d860 --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/pom.xml @@ -0,0 +1,19 @@ + + + + 02-springAMQP + org.example + 1.0-SNAPSHOT + + 4.0.0 + + AMQPPublisher + + + 17 + 17 + + + \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/main/java/com/novice/mq/MQApplication.java b/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/main/java/com/novice/mq/MQApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..9177172c5c9e4374b9ee1906a7febc893f8a41ea --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/main/java/com/novice/mq/MQApplication.java @@ -0,0 +1,11 @@ +package com.novice.mq; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MQApplication { + public static void main(String[] args) { + SpringApplication.run(MQApplication.class, args); + } +} diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/main/resources/application.yml b/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..566a6b51bf67ef6e298aa6aab1a8d27b5020537a --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/main/resources/application.yml @@ -0,0 +1,10 @@ +logging: + pattern: + dateformat: yyyy-MM-dd HH:mm:ss +spring: + rabbitmq: + host: 47.109.145.220 # rabbitmq IP地址 + port: 5672 + username: itcast + password: 123321 + virtual-host: / diff --git a/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/test/java/com/novice/mq/MQProducerTest.java b/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/test/java/com/novice/mq/MQProducerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..35c70e67a315ee0ffcf9fc871d39fb8887089ddd --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/AMQPPublisher/src/test/java/com/novice/mq/MQProducerTest.java @@ -0,0 +1,67 @@ +package com.novice.mq; + +import org.junit.jupiter.api.Test; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + + +@SpringBootTest +public class MQProducerTest { + @Autowired + private RabbitTemplate rabbitTemplate; + + @Test + void contextLoads() { + } + + @Test + public void testSendMsgForSimpleQueue() { + String queueName = "simple.queue"; + String msg = "hello simple.queue"; + rabbitTemplate.convertAndSend(queueName, msg); + } + + @Test + public void testSendMsgForWorkQueue() throws InterruptedException { + // rabbitMQ 会报异常:不能找到队列「原因:rabbitMQ不能自动创建队列」 + String queueName = "work.queue"; + for (int i = 0; i < 50; i++) { + String msg = "hello WorkQueue__" + i; + rabbitTemplate.convertAndSend(queueName, msg); + System.out.println("i = " + i); + } + } + + // 发布订阅模式---通过fanout交换机转发 + @Test + public void testSendMsgForPublishSubscribeAndFanout() throws InterruptedException { + String exchange = "exchange_fanout"; + String msg = "hello WorkQueue__"; + rabbitTemplate.convertAndSend(exchange,"", msg); + } + + // 发布订阅模式---通过direct交换机转发 + @Test + public void testSendMsgForPublishSubscribeAndDirect() throws InterruptedException { + String exchange = "exchange_direct"; + String msg = "hello WorkQueue__red"; + rabbitTemplate.convertAndSend(exchange,"red", msg); + System.out.println("============="); + msg = "hello WorkQueue__blue"; + rabbitTemplate.convertAndSend(exchange,"blue", msg); + System.out.println("============="); + msg = "hello WorkQueue__yellow"; + rabbitTemplate.convertAndSend(exchange,"yellow", msg); + } + + // 发布订阅模式---通过topic交换机转发 + @Test + public void testSendMsgForPublishSubscribeAndTopic() { + String exchange = "exchange_topic"; + String msg = "杨倬 china.weather"; +// rabbitTemplate.convertAndSend(exchange,"china.news", msg); + rabbitTemplate.convertAndSend(exchange,"china.weather", msg); + } + +} diff --git a/02-framework/rabbitmq-demo/02-springAMQP/pom.xml b/02-framework/rabbitmq-demo/02-springAMQP/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..7cf43f830441fd19dddf1f5f169f64ce1e49a573 --- /dev/null +++ b/02-framework/rabbitmq-demo/02-springAMQP/pom.xml @@ -0,0 +1,29 @@ + + + + rabbitmq-demo + org.example + 1.0-SNAPSHOT + + 4.0.0 + + 02-springAMQP + pom + + AMQPPublisher + + + + 17 + 17 + + + + org.springframework.boot + spring-boot-starter-test + + + + \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/assert/img.png b/02-framework/rabbitmq-demo/assert/img.png new file mode 100644 index 0000000000000000000000000000000000000000..24a459d7282ee5c772be868d2921179ca642f321 Binary files /dev/null and b/02-framework/rabbitmq-demo/assert/img.png differ diff --git a/02-framework/rabbitmq-demo/assert/mq.md b/02-framework/rabbitmq-demo/assert/mq.md new file mode 100644 index 0000000000000000000000000000000000000000..3a59fab18799a51381fe0764ced2076b43d4bfdf --- /dev/null +++ b/02-framework/rabbitmq-demo/assert/mq.md @@ -0,0 +1,2 @@ +### 1、简单消息队列 +![img.png](img.png) \ No newline at end of file diff --git a/02-framework/rabbitmq-demo/pom.xml b/02-framework/rabbitmq-demo/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..aa8815f2a850ea76573ef84b7ce6ee628499a427 --- /dev/null +++ b/02-framework/rabbitmq-demo/pom.xml @@ -0,0 +1,29 @@ + + + + 02-framework + org.example + 1.0-SNAPSHOT + + 4.0.0 + + rabbitmq-demo + pom + + 01-simple-queue + 02-springAMQP + + + + 17 + 17 + + + + org.springframework.boot + spring-boot-starter-amqp + + + \ No newline at end of file diff --git a/README.md b/README.md index e2a09055bcc2650985700b63a65adb5c6c89f10c..9fde918ddec477081b0ff860754bc0b326efb0b3 100644 --- a/README.md +++ b/README.md @@ -2,3 +2,21 @@ #### 介绍 记录学习java的过程 + +```xml +FROM openjdk:17 + +WORKDIR /app +# 将jar包添加到容器中并更名 +ADD xxxx.jar /app/app.jar + +#暴露8080端口 +EXPOSE 8080 + +ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app/app.jar"] + + + +```xml +docker build -f Dockerfile -t myimage/trade-jar:latest . --no-cache +docker run -d --name test-jar -p 8080:8080 myimage/trade-jar:latest