马府强
2 years ago
16 changed files with 589 additions and 0 deletions
@ -0,0 +1,33 @@ |
|||
HELP.md |
|||
target/ |
|||
!.mvn/wrapper/maven-wrapper.jar |
|||
!**/src/main/**/target/ |
|||
!**/src/test/**/target/ |
|||
|
|||
### STS ### |
|||
.apt_generated |
|||
.classpath |
|||
.factorypath |
|||
.project |
|||
.settings |
|||
.springBeans |
|||
.sts4-cache |
|||
|
|||
### IntelliJ IDEA ### |
|||
.idea |
|||
*.iws |
|||
*.iml |
|||
*.ipr |
|||
|
|||
### NetBeans ### |
|||
/nbproject/private/ |
|||
/nbbuild/ |
|||
/dist/ |
|||
/nbdist/ |
|||
/.nb-gradle/ |
|||
build/ |
|||
!**/src/main/**/build/ |
|||
!**/src/test/**/build/ |
|||
|
|||
### VS Code ### |
|||
.vscode/ |
@ -0,0 +1,11 @@ |
|||
# demo-request-scope |
|||
|
|||
《基于ThreadLocal实现一个上下文管理组件》技术博客对应源码 |
|||
|
|||
https://juejin.cn/post/7153287656624324638 |
|||
|
|||
本文基于`ThreadLocal`原理,实现了一个上下文状态管理组件`Scope`,通过开启一个自定义的`Scope`,在`Scope`范围内,可以通过`Scope`各个方法读写数据; |
|||
|
|||
通过自定义线程池实现上下文状态数据的线程间传递; |
|||
|
|||
提出了一种基于`Filter`和`Scope`的`Request`粒度的上下文管理方案。 |
@ -0,0 +1,82 @@ |
|||
<?xml version="1.0" encoding="UTF-8"?> |
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> |
|||
<modelVersion>4.0.0</modelVersion> |
|||
<parent> |
|||
<groupId>org.springframework.boot</groupId> |
|||
<artifactId>spring-boot-starter-parent</artifactId> |
|||
<version>2.7.4</version> |
|||
<relativePath/> <!-- lookup parent from repository --> |
|||
</parent> |
|||
<groupId>com.example</groupId> |
|||
<artifactId>demo-request-scope</artifactId> |
|||
<version>0.0.1-SNAPSHOT</version> |
|||
<name>demo-request-scope</name> |
|||
<description>Demo project for Spring Boot</description> |
|||
<properties> |
|||
<java.version>8</java.version> |
|||
</properties> |
|||
|
|||
|
|||
<dependencies> |
|||
|
|||
<dependency> |
|||
<groupId>org.drools</groupId> |
|||
<artifactId>drools-core</artifactId> |
|||
<version>7.59.0.Final</version> |
|||
</dependency> |
|||
<dependency> |
|||
<groupId>org.drools</groupId> |
|||
<artifactId>drools-compiler</artifactId> |
|||
<version>7.59.0.Final</version> |
|||
</dependency> |
|||
<dependency> |
|||
<groupId>org.drools</groupId> |
|||
<artifactId>drools-decisiontables</artifactId> |
|||
<version>7.59.0.Final</version> |
|||
</dependency> |
|||
|
|||
<dependency> |
|||
<groupId>com.google.guava</groupId> |
|||
<artifactId>guava</artifactId> |
|||
<version>30.1-jre</version> |
|||
</dependency> |
|||
|
|||
<dependency> |
|||
<groupId>org.springframework.boot</groupId> |
|||
<artifactId>spring-boot-starter-aop</artifactId> |
|||
</dependency> |
|||
|
|||
|
|||
<dependency> |
|||
<groupId>org.springframework.boot</groupId> |
|||
<artifactId>spring-boot-starter-web</artifactId> |
|||
</dependency> |
|||
|
|||
<dependency> |
|||
<groupId>org.springframework.boot</groupId> |
|||
<artifactId>spring-boot-starter-test</artifactId> |
|||
<scope>test</scope> |
|||
</dependency> |
|||
|
|||
<dependency> |
|||
<groupId>org.projectlombok</groupId> |
|||
<artifactId>lombok</artifactId> |
|||
<optional>true</optional> |
|||
</dependency> |
|||
<dependency> |
|||
<groupId>junit</groupId> |
|||
<artifactId>junit</artifactId> |
|||
</dependency> |
|||
</dependencies> |
|||
|
|||
<build> |
|||
<plugins> |
|||
<plugin> |
|||
<groupId>org.springframework.boot</groupId> |
|||
<artifactId>spring-boot-maven-plugin</artifactId> |
|||
</plugin> |
|||
</plugins> |
|||
</build> |
|||
|
|||
</project> |
@ -0,0 +1,13 @@ |
|||
package com.example.demo; |
|||
|
|||
import org.springframework.boot.SpringApplication; |
|||
import org.springframework.boot.autoconfigure.SpringBootApplication; |
|||
|
|||
@SpringBootApplication |
|||
public class DemoRequestScopeApplication { |
|||
|
|||
public static void main(String[] args) { |
|||
SpringApplication.run(DemoRequestScopeApplication.class, args); |
|||
} |
|||
|
|||
} |
@ -0,0 +1,101 @@ |
|||
package com.example.demo.aop; |
|||
|
|||
import com.example.demo.constants.GloablConstants; |
|||
import org.aspectj.lang.JoinPoint; |
|||
import org.aspectj.lang.ProceedingJoinPoint; |
|||
import org.aspectj.lang.annotation.AfterThrowing; |
|||
import org.aspectj.lang.annotation.Around; |
|||
import org.aspectj.lang.annotation.Aspect; |
|||
import org.aspectj.lang.annotation.Pointcut; |
|||
import org.slf4j.Logger; |
|||
import org.slf4j.LoggerFactory; |
|||
import org.springframework.core.env.Environment; |
|||
import org.springframework.core.env.Profiles; |
|||
import org.springframework.stereotype.Component; |
|||
|
|||
import java.util.Arrays; |
|||
|
|||
@Aspect |
|||
@Component |
|||
public class LoggingAspect { |
|||
|
|||
private final Logger log = LoggerFactory.getLogger(this.getClass()); |
|||
|
|||
private final Environment env; |
|||
|
|||
public LoggingAspect(Environment env) { |
|||
this.env = env; |
|||
} |
|||
|
|||
/** |
|||
* 匹配spring框架的repositories、service、rest端点的切面 |
|||
*/ |
|||
@Pointcut("within(@org.springframework.stereotype.Repository *)" + |
|||
" || within(@org.springframework.stereotype.Service *)" + |
|||
" || within(@org.springframework.web.bind.annotation.RestController *)") |
|||
public void springBeanPointcut() { |
|||
// 方法为空,因为这只是一个切入点,实现在通知中。
|
|||
} |
|||
|
|||
/** |
|||
* 匹配我们自己项目的repositories、service、rest端点的切面 |
|||
*/ |
|||
@Pointcut("within(com.example.demo.config..*)" + |
|||
" || within(com.example.demo.service..*)" + |
|||
" || within(com.example.demo.controller.OrderDiscountController..*)") |
|||
public void applicationPackagePointcut() { |
|||
// 方法为空,因为这只是一个切入点,实现在通知中。
|
|||
} |
|||
|
|||
/** |
|||
* 记录方法抛出异常的通知 |
|||
* |
|||
* @param joinPoint join point for advice |
|||
* @param e exception |
|||
*/ |
|||
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") |
|||
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { |
|||
|
|||
// 判断环境,dev、test or prod
|
|||
if (env.acceptsProfiles(Profiles.of(GloablConstants.SPRING_PROFILE_DEVELOPMENT, GloablConstants.SPRING_PROFILE_TEST))) { |
|||
log.error("Exception in {}.{}() with cause = '{}' and exception = '{}'", joinPoint.getSignature().getDeclaringTypeName(), |
|||
joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL", e.getMessage(), e); |
|||
|
|||
} else { |
|||
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), |
|||
joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL"); |
|||
} |
|||
|
|||
} |
|||
|
|||
/** |
|||
* 在方法进入和退出时记录日志的通知 |
|||
* |
|||
* @param joinPoint join point for advice |
|||
* @return result |
|||
* @throws Throwable throws IllegalArgumentException |
|||
*/ |
|||
@Around("applicationPackagePointcut() && springBeanPointcut()") |
|||
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { |
|||
|
|||
if (log.isDebugEnabled()) { |
|||
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), |
|||
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); |
|||
} |
|||
try { |
|||
Object result = joinPoint.proceed(); |
|||
if (log.isDebugEnabled()) { |
|||
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), |
|||
joinPoint.getSignature().getName(), result); |
|||
} |
|||
return result; |
|||
} catch (IllegalArgumentException e) { |
|||
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), |
|||
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); |
|||
|
|||
throw e; |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
@ -0,0 +1,10 @@ |
|||
package com.example.demo.constants; |
|||
|
|||
|
|||
public interface GloablConstants { |
|||
|
|||
String SPRING_PROFILE_DEVELOPMENT = "dev"; |
|||
String SPRING_PROFILE_TEST = "test"; |
|||
|
|||
|
|||
} |
@ -0,0 +1,30 @@ |
|||
package com.example.demo.controller; |
|||
|
|||
import com.example.demo.service.AopLogService; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.http.ResponseEntity; |
|||
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; |
|||
|
|||
/** |
|||
* 超简洁!SpringBoot使用AOP统一日志管理 |
|||
*/ |
|||
@RestController |
|||
@RequestMapping("/api") |
|||
@Slf4j |
|||
public class TestController { |
|||
|
|||
private final AopLogService aopLogService; |
|||
|
|||
public TestController(AopLogService aopLogService) { |
|||
this.aopLogService = aopLogService; |
|||
} |
|||
|
|||
@GetMapping("/test/{id}") |
|||
public ResponseEntity<String> test(@PathVariable("id") Integer id) { |
|||
return ResponseEntity.ok().body(aopLogService.test(id)); |
|||
} |
|||
|
|||
} |
@ -0,0 +1,15 @@ |
|||
package com.example.demo.request; |
|||
|
|||
/** |
|||
* @className: CustomerType |
|||
* @author: woniu |
|||
* @date: 2023/4/25 |
|||
**/ |
|||
public enum CustomerType { |
|||
LOYAL, NEW, DISSATISFIED; |
|||
|
|||
public String getValue() { |
|||
return this.toString(); |
|||
} |
|||
|
|||
} |
@ -0,0 +1,15 @@ |
|||
package com.example.demo.request; |
|||
|
|||
|
|||
import lombok.Getter; |
|||
import lombok.Setter; |
|||
|
|||
@Getter |
|||
@Setter |
|||
public class OrderDiscount { |
|||
|
|||
/** |
|||
* 折扣 |
|||
*/ |
|||
private Integer discount = 0; |
|||
} |
@ -0,0 +1,26 @@ |
|||
package com.example.demo.request; |
|||
|
|||
|
|||
import lombok.Getter; |
|||
import lombok.Setter; |
|||
|
|||
@Getter |
|||
@Setter |
|||
public class OrderRequest { |
|||
/** |
|||
* 客户号 |
|||
*/ |
|||
private String customerNumber; |
|||
/** |
|||
* 年龄 |
|||
*/ |
|||
private Integer age; |
|||
/** |
|||
* 订单金额 |
|||
*/ |
|||
private Integer amount; |
|||
/** |
|||
* 客户类型 |
|||
*/ |
|||
private CustomerType customerType; |
|||
} |
@ -0,0 +1,16 @@ |
|||
package com.example.demo.service; |
|||
|
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
|
|||
/** |
|||
* AOP统一日志管理测试服务 |
|||
*/ |
|||
@Service |
|||
@Slf4j |
|||
public class AopLogService { |
|||
|
|||
public String test(Integer id) { |
|||
return "传入的参数是:" + id; |
|||
} |
|||
} |
@ -0,0 +1 @@ |
|||
|
@ -0,0 +1,7 @@ |
|||
server: |
|||
port: 8888 |
|||
|
|||
# 环境:dev-开发 test-测试 prod-生产 |
|||
spring: |
|||
profiles: |
|||
active: dev |
@ -0,0 +1,19 @@ |
|||
<?xml version="1.0" encoding="UTF-8"?> |
|||
<configuration> |
|||
<include resource="org/springframework/boot/logging/logback/base.xml" /> |
|||
<logger name="org.springframework.web" level="INFO"/> |
|||
<logger name="org.springboot.sample" level="TRACE" /> |
|||
|
|||
<springProfile name="dev,test"> |
|||
<logger name="org.springframework.web" level="INFO"/> |
|||
<logger name="org.springboot.sample" level="INFO" /> |
|||
<logger name="com.example.demo" level="DEBUG" /> |
|||
</springProfile> |
|||
|
|||
<springProfile name="prod"> |
|||
<logger name="org.springframework.web" level="ERROR"/> |
|||
<logger name="org.springboot.sample" level="ERROR" /> |
|||
<logger name="com.example.demo" level="INFO" /> |
|||
</springProfile> |
|||
|
|||
</configuration> |
@ -0,0 +1,38 @@ |
|||
package rules |
|||
|
|||
import com.example.demo.request.OrderRequest; |
|||
import com.example.demo.request.CustomerType; |
|||
|
|||
global com.example.demo.request.OrderDiscount orderDiscount; |
|||
|
|||
dialect "mvel" |
|||
|
|||
// 规则1: 根据年龄判断 |
|||
rule "Age based discount" |
|||
when |
|||
// 当客户年龄在20岁以下或者50岁以上 |
|||
OrderRequest(age < 20 || age > 50) |
|||
then |
|||
// 则添加10%的折扣 |
|||
System.out.println("==========Adding 10% discount for Kids/ senior customer============="); |
|||
orderDiscount.setDiscount(orderDiscount.getDiscount() + 10); |
|||
end |
|||
|
|||
// 规则2: 根据客户类型的规则 |
|||
rule "Customer type based discount - Loyal customer" |
|||
when |
|||
// 当客户类型是LOYAL |
|||
OrderRequest(customerType.getValue == "LOYAL") |
|||
then |
|||
// 则增加5%的折扣 |
|||
System.out.println("==========Adding 5% discount for LOYAL customer============="); |
|||
orderDiscount.setDiscount(orderDiscount.getDiscount() + 5); |
|||
end |
|||
|
|||
rule "Customer type based discount - others" |
|||
when |
|||
OrderRequest(customerType.getValue != "LOYAL") |
|||
then |
|||
System.out.println("==========Adding 3% discount for NEW or DISSATISFIED customer============="); |
|||
orderDiscount.setDiscount(orderDiscount.getDiscount() + 3); |
|||
end |
@ -0,0 +1,172 @@ |
|||
package com.example.demo.testscope; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import org.junit.jupiter.api.Test; |
|||
|
|||
import java.util.*; |
|||
import java.util.stream.Collectors; |
|||
import java.util.stream.Stream; |
|||
|
|||
public class TestMain { |
|||
|
|||
//工作中常用的一些Stream流操作,多年实践总结
|
|||
|
|||
/** |
|||
* 演示map的用途:一对一转换 |
|||
*/ |
|||
@Test |
|||
public void stringToIntMap() { |
|||
List<String> ids = Arrays.asList("205", "105", "308", "469", "627", "193", "111"); |
|||
// 使用流操作
|
|||
List<User> results = ids.stream() |
|||
.map(id -> { |
|||
User user = new User(Integer.valueOf(id)); |
|||
return user; |
|||
}) |
|||
.collect(Collectors.toList()); |
|||
System.out.println(results); |
|||
} |
|||
|
|||
|
|||
/** |
|||
* 演示map的用途:一对多转换 |
|||
*/ |
|||
@Test |
|||
public void stringToIntFlatmap() { |
|||
List<String> sentences = Arrays.asList("hello world", "Jia Gou Wu Dao"); |
|||
// 使用流操作
|
|||
List<String> results = sentences.stream() |
|||
.flatMap(sentence -> Arrays.stream(sentence.split(" "))) |
|||
.collect(Collectors.toList()); |
|||
System.out.println(results); |
|||
} |
|||
|
|||
|
|||
|
|||
|
|||
|
|||
/** |
|||
*filter、sorted、distinct、limit |
|||
*/ |
|||
@Test |
|||
public void testGetTargetUsers() { |
|||
List<String> ids = Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193"); |
|||
// 使用流操作
|
|||
List<User> results = ids.stream() |
|||
.filter(s -> s.length() > 2) |
|||
.distinct() |
|||
.map(Integer::valueOf) |
|||
.sorted(Comparator.comparingInt(o -> o)) |
|||
.limit(3) |
|||
.map(id -> new User(id)) |
|||
.collect(Collectors.toList()); |
|||
System.out.println(results); |
|||
} |
|||
|
|||
|
|||
|
|||
|
|||
/** |
|||
* 简单结果终止方法 |
|||
*/ |
|||
@Test |
|||
public void testSimpleStopOptions() { |
|||
List<String> ids = Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193"); |
|||
// 统计stream操作后剩余的元素个数
|
|||
System.out.println(ids.stream().filter(s -> s.length() > 2).count()); |
|||
// 判断是否有元素值等于205
|
|||
System.out.println(ids.stream().filter(s -> s.length() > 2).anyMatch("205"::equals)); |
|||
// findFirst操作
|
|||
ids.stream().filter(s -> s.length() > 2) |
|||
.findFirst() |
|||
.ifPresent(s -> System.out.println("findFirst:" + s)); |
|||
} |
|||
|
|||
|
|||
|
|||
|
|||
|
|||
/** |
|||
* 一旦一个Stream被执行了终止操作之后,后续便不可以再读这个流执行其他的操作了,否则会报错 |
|||
*/ |
|||
@Test |
|||
public void testHandleStreamAfterClosed() { |
|||
List<String> ids = Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193"); |
|||
Stream<String> stream = ids.stream().filter(s -> s.length() > 2); |
|||
// 统计stream操作后剩余的元素个数
|
|||
System.out.println(stream.count()); |
|||
System.out.println("-----下面会报错-----"); |
|||
// 判断是否有元素值等于205
|
|||
try { |
|||
System.out.println(stream.anyMatch("205"::equals)); |
|||
} catch (Exception e) { |
|||
e.printStackTrace(); |
|||
} |
|||
System.out.println("-----上面会报错-----"); |
|||
} |
|||
|
|||
|
|||
/** |
|||
* 生成集合 |
|||
*/ |
|||
@Test |
|||
public void testCollectStopOptions() { |
|||
List<User> ids = Arrays.asList(new User(17), new User(22), new User(23)); |
|||
// collect成list
|
|||
List<User> collectList = ids.stream().filter(dept -> dept.getId() > 20) |
|||
.collect(Collectors.toList()); |
|||
System.out.println("collectList:" + collectList); |
|||
// collect成Set
|
|||
Set<User> collectSet = ids.stream().filter(dept -> dept.getId() > 20) |
|||
.collect(Collectors.toSet()); |
|||
System.out.println("collectSet:" + collectSet); |
|||
// collect成HashMap,key为id,value为Dept对象
|
|||
Map<Integer, User> collectMap = ids.stream().filter(dept -> dept.getId() > 20) |
|||
.collect(Collectors.toMap(com.example.demo.testscope.User::getId, dept -> dept)); |
|||
System.out.println("collectMap:" + collectMap); |
|||
} |
|||
|
|||
|
|||
|
|||
|
|||
/** |
|||
* 生成拼接字符串 |
|||
*/ |
|||
@Test |
|||
public void testCollectJoinStrings() { |
|||
List<String> ids = Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193"); |
|||
String joinResult = ids.stream().collect(Collectors.joining(",")); |
|||
System.out.println("拼接后:" + joinResult); |
|||
} |
|||
|
|||
|
|||
|
|||
|
|||
|
|||
/** |
|||
* 数学运算 |
|||
*/ |
|||
@Test |
|||
public void testNumberCalculate() { |
|||
List<Integer> ids = Arrays.asList(10, 20, 30, 40, 50); |
|||
// 计算平均值
|
|||
Double average = ids.stream().collect(Collectors.averagingInt(value -> value)); |
|||
System.out.println("平均值:" + average); |
|||
// 数据统计信息
|
|||
IntSummaryStatistics summary = ids.stream().collect(Collectors.summarizingInt(value -> value)); |
|||
System.out.println("数据统计信息: " + summary); |
|||
} |
|||
|
|||
|
|||
|
|||
|
|||
} |
|||
|
|||
|
|||
@Data |
|||
@AllArgsConstructor |
|||
class User { |
|||
private int id; |
|||
|
|||
} |
Loading…
Reference in new issue