From fd269d89014b0d17a7d0f55e87911c0657a5330c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=B0=B8=E4=BA=AE?= Date: Tue, 26 Apr 2022 21:42:57 +0800 Subject: [PATCH 1/4] Changes --- pom.xml | 1 + spring-boot/pom.xml | 33 +++++++++++++++++++ spring-boot/spring-boot-drools/pom.xml | 22 +++++++++++++ .../test/java/com/wyl/example/AppTest.java | 20 +++++++++++ 4 files changed, 76 insertions(+) create mode 100644 spring-boot/pom.xml create mode 100644 spring-boot/spring-boot-drools/pom.xml create mode 100644 spring-boot/spring-boot-drools/src/test/java/com/wyl/example/AppTest.java diff --git a/pom.xml b/pom.xml index a691a25..af47679 100644 --- a/pom.xml +++ b/pom.xml @@ -13,6 +13,7 @@ concurrent file-read kafka + spring-boot pom diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml new file mode 100644 index 0000000..77d1730 --- /dev/null +++ b/spring-boot/pom.xml @@ -0,0 +1,33 @@ + + + + JavaBasiceDemo + com.wyl.example + 1.0-SNAPSHOT + + + 4.0.0 + + spring-boot-drools + + + spring-boot + pom + A Camel Spring Route + + UTF-8 + UTF-8 + + + + + org.springframework.boot + spring-boot-dependencies + 2.3.12.RELEASE + pom + import + + + + diff --git a/spring-boot/spring-boot-drools/pom.xml b/spring-boot/spring-boot-drools/pom.xml new file mode 100644 index 0000000..39a98e5 --- /dev/null +++ b/spring-boot/spring-boot-drools/pom.xml @@ -0,0 +1,22 @@ + + + + + spring-boot + com.wyl.example + 1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + spring-boot-drools + spring-boot-drools + + UTF-8 + 1.8 + 1.8 + + + + + diff --git a/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/AppTest.java b/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/AppTest.java new file mode 100644 index 0000000..70b9b96 --- /dev/null +++ b/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/AppTest.java @@ -0,0 +1,20 @@ +package com.wyl.example; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Unit test for simple App. + */ +public class AppTest +{ + /** + * Rigorous Test :-) + */ + @Test + public void shouldAnswerWithTrue() + { + assertTrue( true ); + } +} From b82f9c8e26118947cbe91a2893bdcc69124f8eea Mon Sep 17 00:00:00 2001 From: wyl <959814898@qq.com> Date: Tue, 26 Apr 2022 23:50:19 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=E6=B5=8B=E8=AF=95xxjob?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 19 ++- redis/pom.xml | 25 ++++ .../com/wyl/demo/redission/RedisLock.java | 31 ++++ .../com/wyl/demo/redission/RedisObject.java | 16 ++ .../wyl/demo/redission/conf/RedissonConf.java | 32 ++++ .../com/wyl/demo/redission/RedissonTest.java | 57 +++++++ spring-boot/pom.xml | 3 +- spring-boot/spring-boot-xxjob/pom.xml | 68 +++++++++ .../SpringBootXxjobApplication.java | 13 ++ .../config/JobServerConfig.java | 46 ++++++ .../config/RestTemplateConfig.java | 34 +++++ .../service/DynamicXxlJobService.java | 140 ++++++++++++++++++ .../src/main/resources/application.properties | 7 + .../com/wyl/springbootxxjob/BaseTest.java | 15 ++ .../SpringBootXxjobApplicationTests.java | 17 +++ 15 files changed, 521 insertions(+), 2 deletions(-) create mode 100644 redis/pom.xml create mode 100644 redis/src/main/java/com/wyl/demo/redission/RedisLock.java create mode 100644 redis/src/main/java/com/wyl/demo/redission/RedisObject.java create mode 100644 redis/src/main/java/com/wyl/demo/redission/conf/RedissonConf.java create mode 100644 redis/src/test/java/com/wyl/demo/redission/RedissonTest.java create mode 100644 spring-boot/spring-boot-xxjob/pom.xml create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/SpringBootXxjobApplication.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/JobServerConfig.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/RestTemplateConfig.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/service/DynamicXxlJobService.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/resources/application.properties create mode 100644 spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/BaseTest.java create mode 100644 spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/SpringBootXxjobApplicationTests.java diff --git a/pom.xml b/pom.xml index af47679..80de8b4 100644 --- a/pom.xml +++ b/pom.xml @@ -14,6 +14,7 @@ file-read kafka spring-boot + redis pom @@ -27,13 +28,24 @@ cglib 3.3.0 + + org.redisson + redisson + 3.13.4 + org.apache.kafka kafka-clients 2.8.1 + + com.xuxueli + xxl-job-core + 2.3.0 + + @@ -47,6 +59,12 @@ 5.8.2 test + + org.junit.jupiter + junit-jupiter-api + 5.8.2 + test + ch.qos.logback logback-core @@ -57,6 +75,5 @@ logback-classic 1.2.3 - \ No newline at end of file diff --git a/redis/pom.xml b/redis/pom.xml new file mode 100644 index 0000000..2451091 --- /dev/null +++ b/redis/pom.xml @@ -0,0 +1,25 @@ + + + + JavaBasiceDemo + com.wyl.example + 1.0-SNAPSHOT + + 4.0.0 + + redis + + + 8 + 8 + + + + org.redisson + redisson + + + + \ No newline at end of file diff --git a/redis/src/main/java/com/wyl/demo/redission/RedisLock.java b/redis/src/main/java/com/wyl/demo/redission/RedisLock.java new file mode 100644 index 0000000..59146be --- /dev/null +++ b/redis/src/main/java/com/wyl/demo/redission/RedisLock.java @@ -0,0 +1,31 @@ +package com.wyl.demo.redission; + +import com.wyl.demo.redission.conf.RedissonConf; +import org.redisson.api.RLock; +import org.redisson.api.RedissonClient; + +public class RedisLock extends Thread { + + static RedissonClient redissonClient = RedissonConf.getRedissonClient(); + + @Override + public void run() { + lock(); + } + + public void lock() { + RLock lock = redissonClient.getLock("wyl_lock"); + lock.lock(); + try { + System.out.println("获取到锁了"); + Thread.sleep(5000000); + } + catch (InterruptedException e) { + System.err.println(e); + } + finally { + System.out.println("解锁了"); + lock.unlock(); + } + } +} diff --git a/redis/src/main/java/com/wyl/demo/redission/RedisObject.java b/redis/src/main/java/com/wyl/demo/redission/RedisObject.java new file mode 100644 index 0000000..6ea5472 --- /dev/null +++ b/redis/src/main/java/com/wyl/demo/redission/RedisObject.java @@ -0,0 +1,16 @@ +package com.wyl.demo.redission; + +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.List; + +@Data +public class RedisObject implements Serializable { + String name; + LocalDateTime createTime; + Long time; + List tmp = Arrays.asList("123", "234", "345"); +} diff --git a/redis/src/main/java/com/wyl/demo/redission/conf/RedissonConf.java b/redis/src/main/java/com/wyl/demo/redission/conf/RedissonConf.java new file mode 100644 index 0000000..26a2cab --- /dev/null +++ b/redis/src/main/java/com/wyl/demo/redission/conf/RedissonConf.java @@ -0,0 +1,32 @@ +package com.wyl.demo.redission.conf; + +import org.redisson.Redisson; +import org.redisson.api.RedissonClient; +import org.redisson.config.Config; + +/** + * + * @ClassName: RedissonConf + * @Date: 2022/3/3 22:37 + * @author wangyl + * @version V1.0 + */ +public class RedissonConf { + + private volatile static RedissonClient redissonClient; + + public static RedissonClient getRedissonClient() { + if (redissonClient == null) { + synchronized (RedissonConf.class) { + if (redissonClient == null) { + Config config = new Config(); + config.useSingleServer() + .setAddress("redis://192.168.123.102:6379") + .setDatabase(0); + return Redisson.create(config); + } + } + } + return redissonClient; + } +} diff --git a/redis/src/test/java/com/wyl/demo/redission/RedissonTest.java b/redis/src/test/java/com/wyl/demo/redission/RedissonTest.java new file mode 100644 index 0000000..0169519 --- /dev/null +++ b/redis/src/test/java/com/wyl/demo/redission/RedissonTest.java @@ -0,0 +1,57 @@ +package com.wyl.demo.redission; + +import com.wyl.demo.redission.conf.RedissonConf; +import org.junit.jupiter.api.Test; +import org.redisson.api.RAtomicDouble; +import org.redisson.api.RBloomFilter; +import org.redisson.api.RBucket; +import org.redisson.api.RedissonClient; + +import java.time.LocalDateTime; +import java.util.concurrent.TimeUnit; + +public class RedissonTest { + @Test + public void RedisStringTest() { + RedissonClient redissonClient = RedissonConf.getRedissonClient(); + RAtomicDouble wyl = redissonClient.getAtomicDouble("wyl"); + double v = wyl.get(); + System.out.println(v); + } + + @Test + public void RedisBloomFilterTest() { + RedissonClient redissonClient = RedissonConf.getRedissonClient(); + RBloomFilter bloomFilter = redissonClient.getBloomFilter("bloomFilter"); + bloomFilter.tryInit(100, 0); + bloomFilter.add("123"); + bloomFilter.add("124"); + boolean contains = bloomFilter.contains("456"); + long count = bloomFilter.count(); + boolean contains1 = bloomFilter.contains("123"); + System.out.println(count); + } + + @Test + public void RedisObjectTest() { + RedissonClient redissonClient = RedissonConf.getRedissonClient(); + RedisObject redisObject = new RedisObject(); + redisObject.setName("1230"); + redisObject.setCreateTime(LocalDateTime.now()); + redisObject.setTime(123L); + RBucket testObject = redissonClient.getBucket("testObject"); + if (!testObject.isExists()) { + testObject.set(redisObject, 10, TimeUnit.SECONDS); + } + RedisObject redisObject1 = testObject.get(); + System.out.println(redisObject1); + } + + @Test + public void RedisLockTest() throws InterruptedException { + for (int i = 0; i < 100; i++){ + new RedisLock().start(); + } + Thread.sleep(1000000); + } +} diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 77d1730..ea27a3a 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -10,11 +10,12 @@ 4.0.0 spring-boot-drools + spring-boot-xxjob spring-boot pom - A Camel Spring Route + spring-boot UTF-8 UTF-8 diff --git a/spring-boot/spring-boot-xxjob/pom.xml b/spring-boot/spring-boot-xxjob/pom.xml new file mode 100644 index 0000000..63d7da1 --- /dev/null +++ b/spring-boot/spring-boot-xxjob/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + com.wyl.example + spring-boot + 1.0-SNAPSHOT + ../pom.xml + + com.wyl + spring-boot-xxjob + 0.0.1-SNAPSHOT + spring-boot-xxjob + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + com.xuxueli + xxl-job-core + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + com.alibaba + fastjson + 1.2.78 + compile + + + com.squareup.okhttp3 + okhttp + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/SpringBootXxjobApplication.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/SpringBootXxjobApplication.java new file mode 100644 index 0000000..dd65bc3 --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/SpringBootXxjobApplication.java @@ -0,0 +1,13 @@ +package com.wyl.springbootxxjob; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootXxjobApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootXxjobApplication.class, args); + } + +} diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/JobServerConfig.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/JobServerConfig.java new file mode 100644 index 0000000..8809915 --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/JobServerConfig.java @@ -0,0 +1,46 @@ +package com.wyl.springbootxxjob.config; + +import com.xxl.job.core.executor.impl.XxlJobSpringExecutor; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Slf4j +@Configuration +@Getter +public class JobServerConfig { + + @Value("${job.server.admin.addresses}") + private String adminAddresses; + + @Value("${job.server.accessToken}") + private String accessToken; + + @Value("${job.server.executor.appname}") + private String appname; + + @Value("${job.server.executor.address}") + private String address; + + @Value("${job.server.userName}") + private String userName; + + @Value("${job.server.password}") + private String password; + + @Value("${job.server.jobGroup}") + private String jobGroup; + + @Bean + public XxlJobSpringExecutor xxlJobExecutor() { + log.info(">>>>>>>>>>> job-server config init."); + XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); + xxlJobSpringExecutor.setAdminAddresses(adminAddresses); + xxlJobSpringExecutor.setAppname(appname); + xxlJobSpringExecutor.setAddress(address); + xxlJobSpringExecutor.setAccessToken(accessToken); + return xxlJobSpringExecutor; + } +} diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/RestTemplateConfig.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/RestTemplateConfig.java new file mode 100644 index 0000000..1c9af2e --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/RestTemplateConfig.java @@ -0,0 +1,34 @@ +package com.wyl.springbootxxjob.config; + +import okhttp3.OkHttpClient; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +import java.util.concurrent.TimeUnit; + +@Configuration +public class RestTemplateConfig { + + @ConditionalOnMissingBean(RestTemplate.class) + @Bean + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory()); + return restTemplate; + } + + /** + * 使用OkHttpClient作为底层客户端 + * @return + */ + private ClientHttpRequestFactory getClientHttpRequestFactory() { + OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS) + .writeTimeout(5, TimeUnit.SECONDS) + .readTimeout(5, TimeUnit.SECONDS) + .build(); + return new OkHttp3ClientHttpRequestFactory(okHttpClient); + } +} \ No newline at end of file diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/service/DynamicXxlJobService.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/service/DynamicXxlJobService.java new file mode 100644 index 0000000..31fd7ff --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/service/DynamicXxlJobService.java @@ -0,0 +1,140 @@ +package com.wyl.springbootxxjob.service; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.wyl.springbootxxjob.config.JobServerConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; +import javax.annotation.Resource; + +@Service +public class DynamicXxlJobService { + + @Resource + private JobServerConfig jobServerConfig; + + @Autowired + RestTemplate restTemplate; + + /** + * 创建固定任务 + * + * @param desc 任务描述 + * @param corn cron 表达式 + * @param param param + * @return jobId + */ + private int createJob(String cookie, String desc, String corn, String param) { + + int jobId = -1; + MultiValueMap paramMap = new LinkedMultiValueMap<>(); + paramMap.add("jobGroup", jobServerConfig.getJobGroup()); + paramMap.add("jobDesc", desc); + paramMap.add("author", "system_patrol"); + paramMap.add("scheduleType", "CRON"); + paramMap.add("scheduleConf", corn); + paramMap.add("cronGen_display", corn); + paramMap.add("glueType", "BEAN"); + paramMap.add("executorHandler", "patrolGenerateHandler"); + paramMap.add("executorParam", param); + paramMap.add("executorRouteStrategy", "FIRST"); + paramMap.add("misfireStrategy", "DO_NOTHING"); + paramMap.add("executorBlockStrategy", "SERIAL_EXECUTION"); + paramMap.add("executorTimeout", "0"); + paramMap.add("executorFailRetryCount", "0"); + paramMap.add("glueRemark", "GLUE代码初始化"); + paramMap.add("cookie", cookie); + String s = post("", paramMap); + JSONObject jsonObject = JSON.parseObject(s); + int code = jsonObject.getIntValue("code"); + if (code == 200) { + jobId = jsonObject.getIntValue("content"); + } + + return jobId; + } + + + /** + * 启动固定任务 + * @param cookie cookie + * @param jobId jobId + * @return 启动固定任务 + */ + private boolean start(String cookie, int jobId) { + MultiValueMap paramMap = new LinkedMultiValueMap<>(); + paramMap.add("id", String.valueOf(jobId)); + paramMap.add("cookie", "cookie"); + String s = post("", paramMap); + JSONObject jsonObject = JSON.parseObject(s); + int code = jsonObject.getIntValue("code"); + if (code == 200) { + return true; + } + return false; + } + + + /** + * 删除固定任务 + * @param cookie cookie + * @param jobId jobId + * @return 启动固定任务 + */ + public boolean remove(String cookie, int jobId) { + MultiValueMap paramMap = new LinkedMultiValueMap<>(); + paramMap.add("id", String.valueOf(jobId)); + String s = post("", paramMap); + JSONObject jsonObject = JSON.parseObject(s); + int code = jsonObject.getInteger("code"); + if (code == 200) { + return true; + } + return false; + } + + /** + * 获取cookie + * @return 返回cookie值 + */ + public String getCookie() { + String path = jobServerConfig.getAdminAddresses() + "/login"; + + // 请求头设置,x-www-form-urlencoded格式的数据 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + //提交参数设置 + MultiValueMap hashMap = new LinkedMultiValueMap<>(); + // 组装请求体 + hashMap.add("userName", jobServerConfig.getUserName()); + hashMap.add("password", jobServerConfig.getPassword()); + HttpEntity> request = new HttpEntity<>(hashMap, headers); + ResponseEntity stringResponseEntity = restTemplate.postForEntity(path, request, String.class); + return stringResponseEntity.toString(); +// +// List cookies = response.getCookies(); +// StringBuilder sb = new StringBuilder(); +// for (HttpCookie cookie : cookies) { +// sb.append(cookie.toString()); +// } +// return sb.toString(); + } + + public String post(String url, MultiValueMap hashMap) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + HttpEntity> request = new HttpEntity<>(hashMap, headers); + ResponseEntity stringResponseEntity = restTemplate.postForEntity(url, request, String.class); + return stringResponseEntity.getBody(); + } + +} + diff --git a/spring-boot/spring-boot-xxjob/src/main/resources/application.properties b/spring-boot/spring-boot-xxjob/src/main/resources/application.properties new file mode 100644 index 0000000..951ef5b --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/resources/application.properties @@ -0,0 +1,7 @@ +job.server.admin.addresses=http://192.168.123.102:9090/xxl-job-admin +job.server.accessToken=1 +job.server.executor.appname= asd +job.server.executor.address= 192.168.123.148 +job.server.userName=admin +job.server.password=123456 +job.server.jobGroup=1 \ No newline at end of file diff --git a/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/BaseTest.java b/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/BaseTest.java new file mode 100644 index 0000000..40dc8b9 --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/BaseTest.java @@ -0,0 +1,15 @@ +package com.wyl.springbootxxjob; + +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = BaseTest.Application.class) +public class BaseTest { + @ComponentScan(value = "com.wyl.springbootxxjob") + public static class Application { + + } +} \ No newline at end of file diff --git a/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/SpringBootXxjobApplicationTests.java b/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/SpringBootXxjobApplicationTests.java new file mode 100644 index 0000000..39d99ae --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/SpringBootXxjobApplicationTests.java @@ -0,0 +1,17 @@ +package com.wyl.springbootxxjob; + +import com.wyl.springbootxxjob.service.DynamicXxlJobService; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +class SpringBootXxjobApplicationTests extends BaseTest{ + + @Autowired + DynamicXxlJobService dynamicXxlJobService; + @Test + void contextLoads() { + dynamicXxlJobService.getCookie(); + } + +} From fa85a8b2820a1b12058d001375db2ed8e125dbd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=B0=B8=E4=BA=AE?= Date: Thu, 28 Apr 2022 18:56:17 +0800 Subject: [PATCH 3/4] xxl-job-rest --- spring-boot/spring-boot-xxjob/pom.xml | 12 +- .../wyl/springbootxxjob/EnableXxljobRest.java | 13 + .../config/JobServerConfig.java | 56 ++-- .../config/RestTemplateConfig.java | 34 --- .../wyl/springbootxxjob/job/SampleXxlJob.java | 50 ++++ .../wyl/springbootxxjob/job/XxlJobConfig.java | 77 +++++ .../wyl/springbootxxjob/obj/JobEntity.java | 107 +++++++ .../springbootxxjob/obj/JobTriggerEntity.java | 34 +++ .../wyl/springbootxxjob/obj/LoginEntity.java | 29 ++ .../com/wyl/springbootxxjob/obj/Result.java | 31 ++ .../service/DynamicXxlJobService.java | 268 ++++++++++++------ .../src/main/resources/application.properties | 23 +- .../SpringBootXxjobApplicationTests.java | 74 ++++- 13 files changed, 645 insertions(+), 163 deletions(-) create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/EnableXxljobRest.java delete mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/RestTemplateConfig.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/job/SampleXxlJob.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/job/XxlJobConfig.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/JobEntity.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/JobTriggerEntity.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/LoginEntity.java create mode 100644 spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/Result.java diff --git a/spring-boot/spring-boot-xxjob/pom.xml b/spring-boot/spring-boot-xxjob/pom.xml index 63d7da1..ab73768 100644 --- a/spring-boot/spring-boot-xxjob/pom.xml +++ b/spring-boot/spring-boot-xxjob/pom.xml @@ -36,12 +36,12 @@ spring-boot-starter-test test - - com.alibaba - fastjson - 1.2.78 - compile - + + + + + + com.squareup.okhttp3 okhttp diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/EnableXxljobRest.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/EnableXxljobRest.java new file mode 100644 index 0000000..61fec7b --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/EnableXxljobRest.java @@ -0,0 +1,13 @@ +package com.wyl.springbootxxjob; + +import com.wyl.springbootxxjob.config.JobServerConfig; +import org.springframework.context.annotation.Import; + +import java.lang.annotation.*; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Import(JobServerConfig.class) +public @interface EnableXxljobRest { +} diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/JobServerConfig.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/JobServerConfig.java index 8809915..9d5fa8d 100644 --- a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/JobServerConfig.java +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/JobServerConfig.java @@ -1,46 +1,54 @@ package com.wyl.springbootxxjob.config; -import com.xxl.job.core.executor.impl.XxlJobSpringExecutor; +import com.wyl.springbootxxjob.service.DynamicXxlJobService; import lombok.Getter; import lombok.extern.slf4j.Slf4j; +import okhttp3.OkHttpClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +import java.util.concurrent.TimeUnit; + -@Slf4j @Configuration @Getter +@Slf4j public class JobServerConfig { - @Value("${job.server.admin.addresses}") + @Value("${xxl-job.http.serve.admin.addresses}") private String adminAddresses; - @Value("${job.server.accessToken}") - private String accessToken; - - @Value("${job.server.executor.appname}") - private String appname; - - @Value("${job.server.executor.address}") - private String address; - - @Value("${job.server.userName}") + @Value("${xxl-job.http.job.server.userName}") private String userName; - @Value("${job.server.password}") + @Value("${xxl-job.http.job.server.password}") private String password; - @Value("${job.server.jobGroup}") - private String jobGroup; + @Bean("xxJobRestTemplate") + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory()); + return restTemplate; + } @Bean - public XxlJobSpringExecutor xxlJobExecutor() { - log.info(">>>>>>>>>>> job-server config init."); - XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); - xxlJobSpringExecutor.setAdminAddresses(adminAddresses); - xxlJobSpringExecutor.setAppname(appname); - xxlJobSpringExecutor.setAddress(address); - xxlJobSpringExecutor.setAccessToken(accessToken); - return xxlJobSpringExecutor; + DynamicXxlJobService dynamicXxlJobService() { + return new DynamicXxlJobService(); + } + + /** + * 使用OkHttpClient作为底层客户端 + * + * @return + */ + private ClientHttpRequestFactory getClientHttpRequestFactory() { + OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS) + .writeTimeout(5, TimeUnit.SECONDS) + .readTimeout(5, TimeUnit.SECONDS) + .build(); + return new OkHttp3ClientHttpRequestFactory(okHttpClient); } } diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/RestTemplateConfig.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/RestTemplateConfig.java deleted file mode 100644 index 1c9af2e..0000000 --- a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/config/RestTemplateConfig.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.wyl.springbootxxjob.config; - -import okhttp3.OkHttpClient; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; - -import java.util.concurrent.TimeUnit; - -@Configuration -public class RestTemplateConfig { - - @ConditionalOnMissingBean(RestTemplate.class) - @Bean - public RestTemplate restTemplate() { - RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory()); - return restTemplate; - } - - /** - * 使用OkHttpClient作为底层客户端 - * @return - */ - private ClientHttpRequestFactory getClientHttpRequestFactory() { - OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS) - .writeTimeout(5, TimeUnit.SECONDS) - .readTimeout(5, TimeUnit.SECONDS) - .build(); - return new OkHttp3ClientHttpRequestFactory(okHttpClient); - } -} \ No newline at end of file diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/job/SampleXxlJob.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/job/SampleXxlJob.java new file mode 100644 index 0000000..585a4fe --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/job/SampleXxlJob.java @@ -0,0 +1,50 @@ +package com.wyl.springbootxxjob.job; + +import com.xxl.job.core.context.XxlJobHelper; +import com.xxl.job.core.handler.annotation.XxlJob; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.sound.midi.Soundbank; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +/** + * XxlJob开发示例(Bean模式) + *

+ * 开发步骤: + * 1、任务开发:在Spring Bean实例中,开发Job方法; + * 2、注解配置:为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")",注解value值对应的是调度中心新建任务的JobHandler属性的值。 + * 3、执行日志:需要通过 "XxlJobHelper.log" 打印执行日志; + * 4、任务结果:默认任务结果为 "成功" 状态,不需要主动设置;如有诉求,比如设置任务结果为失败,可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果; + * + * @author xuxueli 2019-12-11 21:52:51 + */ +@Component +public class SampleXxlJob { + private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class); + + + /** + * 1、简单任务示例(Bean模式) + */ + @XxlJob("wylDemoHandler") + public void demoJobHandler() throws Exception { + XxlJobHelper.log("XXL-JOB, Hello World."); + System.out.println(XxlJobHelper.getJobParam()); + System.out.println(XxlJobHelper.getJobId()); + for (int i = 0; i < 5; i++) { + XxlJobHelper.log("beat at:" + i); + TimeUnit.SECONDS.sleep(2); + } + // default success + } + +} diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/job/XxlJobConfig.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/job/XxlJobConfig.java new file mode 100644 index 0000000..9214baa --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/job/XxlJobConfig.java @@ -0,0 +1,77 @@ +package com.wyl.springbootxxjob.job; + +import com.xxl.job.core.executor.impl.XxlJobSpringExecutor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * xxl-job config + * + * @author xuxueli 2017-04-28 + */ +@Configuration +public class XxlJobConfig { + private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class); + + @Value("${xxl.job.admin.addresses}") + private String adminAddresses; + + @Value("${xxl.job.accessToken}") + private String accessToken; + + @Value("${xxl.job.executor.appname}") + private String appname; + + @Value("${xxl.job.executor.address}") + private String address; + + @Value("${xxl.job.executor.ip}") + private String ip; + + @Value("${xxl.job.executor.port}") + private int port; + + @Value("${xxl.job.executor.logpath}") + private String logPath; + + @Value("${xxl.job.executor.logretentiondays}") + private int logRetentionDays; + + + @Bean + public XxlJobSpringExecutor xxlJobExecutor() { + logger.info(">>>>>>>>>>> xxl-job config init."); + XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); + xxlJobSpringExecutor.setAdminAddresses(adminAddresses); + xxlJobSpringExecutor.setAppname(appname); + xxlJobSpringExecutor.setAddress(address); + xxlJobSpringExecutor.setIp(ip); + xxlJobSpringExecutor.setPort(port); + xxlJobSpringExecutor.setAccessToken(accessToken); + xxlJobSpringExecutor.setLogPath(logPath); + xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays); + return xxlJobSpringExecutor; + } + + /** + * 针对多网卡、容器内部署等情况,可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP; + * + * 1、引入依赖: + * + * org.springframework.cloud + * spring-cloud-commons + * ${version} + * + * + * 2、配置文件,或者容器启动变量 + * spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.' + * + * 3、获取IP + * String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); + */ + + +} \ No newline at end of file diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/JobEntity.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/JobEntity.java new file mode 100644 index 0000000..c52f7f8 --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/JobEntity.java @@ -0,0 +1,107 @@ +package com.wyl.springbootxxjob.obj; + +import lombok.Data; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +/** + * @author: wangyl + * @date: 2022/4/27 + * @description: 创建任务对象 + */ +@Data +public class JobEntity { + /** + * 任务id 修改是需要填写 + */ + Integer id; + /** + * 执行器主键ID + */ + String jobGroup = ""; + /** + * job描述 + */ + String jobDesc = ""; + /** + * 作者 + */ + String author = "xxl-job-rest"; + /** + * 调度类型 + */ + String scheduleType = "CRON"; + /** + * 调度配置,值含义取决于调度类型 + */ + String scheduleConf = ""; + /** + * 调度过期策略 + */ + String cronGenDisplay = ""; + /** + * + */ + String scheduleConfCRON = ""; + /** + * GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum + */ + String glueType = "BEAN"; + /** + * 执行器,任务Handler名称 + */ + String executorHandler = ""; + /** + * 执行器,任务参数 + */ + String executorParam = ""; + /** + * 执行器路由策略 + */ + String executorRouteStrategy = "FIRST"; + /** + * 调度过期策略 + */ + String misfireStrategy = "DO_NOTHING"; + /** + * 阻塞处理策略 + */ + String executorBlockStrategy = "SERIAL_EXECUTION"; + /** + * 任务执行超时时间,单位秒 + */ + String executorTimeout = "0"; + /** + * 失败重试次数 + */ + String executorFailRetryCount = "0"; + /** + * GLUE备注 + */ + String glueRemark = ""; + + public MultiValueMap makeParam() { + MultiValueMap paramMap = new LinkedMultiValueMap<>(); + paramMap.add("jobGroup", jobGroup); + paramMap.add("jobDesc", jobDesc); + paramMap.add("author", author); + paramMap.add("scheduleType", scheduleType); + paramMap.add("scheduleConf", scheduleConf); + paramMap.add("cronGen_display", cronGenDisplay); + paramMap.add("glueType", glueType); + paramMap.add("executorHandler", executorHandler); + paramMap.add("executorParam", executorParam); + paramMap.add("executorRouteStrategy", executorRouteStrategy); + paramMap.add("misfireStrategy", misfireStrategy); + paramMap.add("executorBlockStrategy", executorBlockStrategy); + paramMap.add("executorTimeout", executorTimeout); + paramMap.add("executorFailRetryCount", executorFailRetryCount); + paramMap.add("glueRemark", glueRemark); + paramMap.add("schedule_conf_CRON", scheduleConfCRON); + if (id != null) { + paramMap.add("id", id.toString()); + } + return paramMap; + } + +} diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/JobTriggerEntity.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/JobTriggerEntity.java new file mode 100644 index 0000000..8d76ec6 --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/JobTriggerEntity.java @@ -0,0 +1,34 @@ +package com.wyl.springbootxxjob.obj; + +import lombok.Data; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +/** + * @author: wangyl + * @date: 2022/4/27 + * @description: 立即执行任务参数 + */ +@Data +public class JobTriggerEntity { + /** + * 任务id + */ + Integer id; + /** + * 执行参数 + */ + String executorParam; + /** + * 执行任务机器ip列表 + */ + String addressList; + + public MultiValueMap makeParam() { + MultiValueMap hashMap = new LinkedMultiValueMap<>(); + hashMap.add("id", id.toString()); + hashMap.add("executorParam", executorParam); + hashMap.add("addressList", addressList); + return hashMap; + } +} diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/LoginEntity.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/LoginEntity.java new file mode 100644 index 0000000..163fc9a --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/LoginEntity.java @@ -0,0 +1,29 @@ +package com.wyl.springbootxxjob.obj; + +import lombok.Data; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +/** + * @author: wangyl + * @date: 2022/4/27 + * @description: xx-job 登录对象 + */ +@Data +public class LoginEntity { + /** + * 用户名 + */ + String userName = ""; + /** + * 密码 + */ + String password = ""; + + public MultiValueMap makeParam() { + MultiValueMap hashMap = new LinkedMultiValueMap<>(); + hashMap.add("userName", userName); + hashMap.add("password", password); + return hashMap; + } +} diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/Result.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/Result.java new file mode 100644 index 0000000..f767e87 --- /dev/null +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/obj/Result.java @@ -0,0 +1,31 @@ +package com.wyl.springbootxxjob.obj; + +import lombok.Data; + +/** + * @author: wangyl + * @date: 2022/4/27 + * @description: xx-job请求返回对象 + */ +@Data +public class Result { + /** + * 操作吗 + */ + private Integer code; + /** + * 错误信息 + */ + private String msg; + /** + * 结果信息 + */ + private T content; + + /** + * 操作成功 + */ + public Boolean succeed() { + return 200 == code; + } +} diff --git a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/service/DynamicXxlJobService.java b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/service/DynamicXxlJobService.java index 31fd7ff..1eb7de2 100644 --- a/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/service/DynamicXxlJobService.java +++ b/spring-boot/spring-boot-xxjob/src/main/java/com/wyl/springbootxxjob/service/DynamicXxlJobService.java @@ -1,139 +1,231 @@ package com.wyl.springbootxxjob.service; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; import com.wyl.springbootxxjob.config.JobServerConfig; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import com.wyl.springbootxxjob.obj.JobEntity; +import com.wyl.springbootxxjob.obj.JobTriggerEntity; +import com.wyl.springbootxxjob.obj.LoginEntity; +import com.wyl.springbootxxjob.obj.Result; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.*; import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; + +import javax.annotation.PostConstruct; import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; @Service +@Slf4j public class DynamicXxlJobService { + /** + * 登录url + */ + static private String LOGIN_URL; + /** + * 创建任务的url + */ + static private String CREATE_JOB; + + /** + * 创建任务的url + */ + static private String UPDATE_JOB; + /** + * 删除任务的url + */ + static private String REMOVE_JOB; + /** + * 启动任务的url + */ + static private String START_JOB; + /** + * 停止任务的url + */ + static private String STOP_JOB; + /** + * 立即执行任务url + */ + static private String TRIGGER_JOB; + + @PostConstruct + public void init() { + LOGIN_URL = jobServerConfig.getAdminAddresses() + "/login"; + CREATE_JOB = jobServerConfig.getAdminAddresses() + "/jobinfo/add"; + UPDATE_JOB = jobServerConfig.getAdminAddresses() + "/jobinfo/update"; + REMOVE_JOB = jobServerConfig.getAdminAddresses() + "/jobinfo/remove"; + START_JOB = jobServerConfig.getAdminAddresses() + "/jobinfo/start"; + STOP_JOB = jobServerConfig.getAdminAddresses() + "/jobinfo/stop"; + TRIGGER_JOB = jobServerConfig.getAdminAddresses() + "/jobinfo/trigger"; + } + @Resource private JobServerConfig jobServerConfig; - @Autowired + @Resource(name = "xxJobRestTemplate") RestTemplate restTemplate; /** - * 创建固定任务 + * 创建定时任务 * - * @param desc 任务描述 - * @param corn cron 表达式 - * @param param param - * @return jobId + * @param jobEntity + * @return java.lang.Integer + * @Date 2022/4/27 + * @Author wangyl */ - private int createJob(String cookie, String desc, String corn, String param) { - - int jobId = -1; - MultiValueMap paramMap = new LinkedMultiValueMap<>(); - paramMap.add("jobGroup", jobServerConfig.getJobGroup()); - paramMap.add("jobDesc", desc); - paramMap.add("author", "system_patrol"); - paramMap.add("scheduleType", "CRON"); - paramMap.add("scheduleConf", corn); - paramMap.add("cronGen_display", corn); - paramMap.add("glueType", "BEAN"); - paramMap.add("executorHandler", "patrolGenerateHandler"); - paramMap.add("executorParam", param); - paramMap.add("executorRouteStrategy", "FIRST"); - paramMap.add("misfireStrategy", "DO_NOTHING"); - paramMap.add("executorBlockStrategy", "SERIAL_EXECUTION"); - paramMap.add("executorTimeout", "0"); - paramMap.add("executorFailRetryCount", "0"); - paramMap.add("glueRemark", "GLUE代码初始化"); - paramMap.add("cookie", cookie); - String s = post("", paramMap); - JSONObject jsonObject = JSON.parseObject(s); - int code = jsonObject.getIntValue("code"); - if (code == 200) { - jobId = jsonObject.getIntValue("content"); + public Integer createJob(JobEntity jobEntity) { + MultiValueMap creatJonParam = jobEntity.makeParam(); + ResponseEntity responseEntity = this.postFrom(CREATE_JOB, creatJonParam, true); + Result body = responseEntity.getBody(); + if (!body.succeed()) { + log.error("创建任务失败,参数为;" + creatJonParam + "错误为:" + body.getMsg()); + throw new RuntimeException(); } - - return jobId; + Object jobId = body.getContent(); + return Integer.valueOf(jobId.toString()); } + /** + * 更新定时任务信息 + * @param jobEntity + * @return boolean + * @Date 2022/4/28 + * @Author wangyl + */ + public boolean updateJob(JobEntity jobEntity) { + MultiValueMap creatJonParam = jobEntity.makeParam(); + ResponseEntity responseEntity = this.postFrom(UPDATE_JOB, creatJonParam, true); + Result body = responseEntity.getBody(); + if (!body.succeed()) { + log.error("更新任务失败,参数为;" + creatJonParam + "错误为:" + body.getMsg()); + throw new RuntimeException(body.getMsg()); + } + return true; + } + public boolean triggerJob(JobTriggerEntity jobTriggerEntity) { + MultiValueMap jobTriggerParam = jobTriggerEntity.makeParam(); + ResponseEntity responseEntity = this.postFrom(TRIGGER_JOB, jobTriggerParam, true); + Result body = responseEntity.getBody(); + if (!body.succeed()) { + log.error("立即执行任务失败,参数为;" + jobTriggerEntity + "错误为:" + body.getMsg()); + throw new RuntimeException(); + } + return true; + } /** * 启动固定任务 - * @param cookie cookie + * * @param jobId jobId * @return 启动固定任务 */ - private boolean start(String cookie, int jobId) { + public boolean startJob(Integer jobId) { MultiValueMap paramMap = new LinkedMultiValueMap<>(); paramMap.add("id", String.valueOf(jobId)); - paramMap.add("cookie", "cookie"); - String s = post("", paramMap); - JSONObject jsonObject = JSON.parseObject(s); - int code = jsonObject.getIntValue("code"); - if (code == 200) { - return true; + ResponseEntity responseEntity = postFrom(START_JOB, paramMap, true); + Result body = responseEntity.getBody(); + if (!body.succeed()) { + log.error("job:" + jobId + "启动失败,失败理由:" + body.getMsg()); + throw new RuntimeException(body.getMsg());//todo 替换异常对象 } - return false; + + return true; + } + + /** + * 停止任务 + * + * @param jobId + * @return boolean + * @Date 2022/4/27 + * @Author wangyl + */ + public boolean stopJob(Integer jobId) { + MultiValueMap paramMap = new LinkedMultiValueMap<>(); + paramMap.add("id", String.valueOf(jobId)); + ResponseEntity responseEntity = postFrom(STOP_JOB, paramMap, true); + Result body = responseEntity.getBody(); + if (!body.succeed()) { + log.error("job:" + jobId + "停止失败,失败理由:" + body.getMsg()); + throw new RuntimeException(body.getMsg());//todo 替换异常对象 + } + + return true; } /** - * 删除固定任务 - * @param cookie cookie - * @param jobId jobId - * @return 启动固定任务 + * 删除指定任务 + * + * @param jobId 任务id + * @return boolean + * @Date 2022/4/27 + * @Author wangyl */ - public boolean remove(String cookie, int jobId) { + public boolean removeJob(Integer jobId) { MultiValueMap paramMap = new LinkedMultiValueMap<>(); paramMap.add("id", String.valueOf(jobId)); - String s = post("", paramMap); - JSONObject jsonObject = JSON.parseObject(s); - int code = jsonObject.getInteger("code"); - if (code == 200) { - return true; + ResponseEntity responseEntity = postFrom(REMOVE_JOB, paramMap, true); + Result body = responseEntity.getBody(); + if (!body.succeed()) { + log.error("job:" + jobId + "删除失败,失败理由:" + body.getMsg()); + throw new RuntimeException(body.getMsg());//todo 替换异常对象 } - return false; + return true; } /** - * 获取cookie - * @return 返回cookie值 + * 登录xx-job获取cookies + * + * @param + * @return java.util.List + * @Date 2022/4/27 + * @Author wangyl */ - public String getCookie() { - String path = jobServerConfig.getAdminAddresses() + "/login"; + public List getCookie() { + LoginEntity loginEntity = new LoginEntity(); + loginEntity.setUserName(jobServerConfig.getUserName()); + loginEntity.setPassword(jobServerConfig.getPassword()); + MultiValueMap loginParam = loginEntity.makeParam(); + ResponseEntity responseEntity = this.postFrom(LOGIN_URL, loginParam, false); + Result result = responseEntity.getBody(); + if (!result.succeed()) { + log.error("登录xx-job失败", result.getMsg()); + throw new RuntimeException(result.getMsg());//todo 替换异常对象 + } + List cookies = responseEntity.getHeaders().get("Set-Cookie"); + return cookies; + } + /** + * 发送post的 form 请求 + * + * @param url 请求url + * @param hashMap 请求参数 + * @return java.lang.String + * @Date 2022/4/27 + * @Author wangyl + */ + public ResponseEntity postFrom(String url, MultiValueMap hashMap, Boolean needCookies) { + HttpHeaders headers = new HttpHeaders(); + List cookies = new ArrayList<>(); + if (needCookies && CollectionUtils.isEmpty(cookies)) { + cookies = getCookie(); + headers.put(HttpHeaders.COOKIE, cookies); + } // 请求头设置,x-www-form-urlencoded格式的数据 - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - //提交参数设置 - MultiValueMap hashMap = new LinkedMultiValueMap<>(); - // 组装请求体 - hashMap.add("userName", jobServerConfig.getUserName()); - hashMap.add("password", jobServerConfig.getPassword()); - HttpEntity> request = new HttpEntity<>(hashMap, headers); - ResponseEntity stringResponseEntity = restTemplate.postForEntity(path, request, String.class); - return stringResponseEntity.toString(); -// -// List cookies = response.getCookies(); -// StringBuilder sb = new StringBuilder(); -// for (HttpCookie cookie : cookies) { -// sb.append(cookie.toString()); -// } -// return sb.toString(); - } - - public String post(String url, MultiValueMap hashMap) { - HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity> request = new HttpEntity<>(hashMap, headers); - ResponseEntity stringResponseEntity = restTemplate.postForEntity(url, request, String.class); - return stringResponseEntity.getBody(); + ResponseEntity responseEntity = restTemplate.postForEntity(url, request, Result.class); + if (!(responseEntity.getStatusCode() == HttpStatus.OK)) { + log.error("请求url:" + url + ",param:" + hashMap + " result:" + responseEntity); + throw new RuntimeException("");//TODO 修改为异常 + } + return responseEntity; } } diff --git a/spring-boot/spring-boot-xxjob/src/main/resources/application.properties b/spring-boot/spring-boot-xxjob/src/main/resources/application.properties index 951ef5b..900cff9 100644 --- a/spring-boot/spring-boot-xxjob/src/main/resources/application.properties +++ b/spring-boot/spring-boot-xxjob/src/main/resources/application.properties @@ -1,7 +1,16 @@ -job.server.admin.addresses=http://192.168.123.102:9090/xxl-job-admin -job.server.accessToken=1 -job.server.executor.appname= asd -job.server.executor.address= 192.168.123.148 -job.server.userName=admin -job.server.password=123456 -job.server.jobGroup=1 \ No newline at end of file +xxl-job.http.serve.admin.addresses=http://192.168.3.10:8080/xxl-job-admin/ +xxl-job.http.job.server.userName = admin +xxl-job.http.job.server.password = 123456 + + + + +### xxl-job admin address list, such as "http://address" or "http://address01,http://address02" +xxl.job.admin.addresses=http://192.168.3.10:8080/xxl-job-admin +xxl.job.accessToken= +xxl.job.executor.appname=wyl-first-test +xxl.job.executor.address= +xxl.job.executor.ip= +xxl.job.executor.port=9999 +xxl.job.executor.logpath=./logs +xxl.job.executor.logretentiondays=30 diff --git a/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/SpringBootXxjobApplicationTests.java b/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/SpringBootXxjobApplicationTests.java index 39d99ae..f0376ac 100644 --- a/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/SpringBootXxjobApplicationTests.java +++ b/spring-boot/spring-boot-xxjob/src/test/java/com/wyl/springbootxxjob/SpringBootXxjobApplicationTests.java @@ -1,17 +1,83 @@ package com.wyl.springbootxxjob; +import com.wyl.springbootxxjob.obj.JobEntity; +import com.wyl.springbootxxjob.obj.JobTriggerEntity; import com.wyl.springbootxxjob.service.DynamicXxlJobService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -class SpringBootXxjobApplicationTests extends BaseTest{ +import java.time.LocalDateTime; +import java.util.List; + +class SpringBootXxjobApplicationTests extends BaseTest { @Autowired DynamicXxlJobService dynamicXxlJobService; + @Test - void contextLoads() { - dynamicXxlJobService.getCookie(); + void getCookiesTest() { + List cookie = dynamicXxlJobService.getCookie(); + System.out.println(cookie); + } + + @Test + void createJobTest() { + JobEntity jobEntity = new JobEntity(); + jobEntity.setJobGroup("2"); + jobEntity.setJobDesc("测试项目"+ LocalDateTime.now()); + jobEntity.setAuthor("wyl"); + jobEntity.setScheduleConf("* * * * * ?"); + jobEntity.setCronGenDisplay("* * * * * ?"); + jobEntity.setGlueType("BEAN"); + jobEntity.setExecutorHandler("wylDemoHandler"); + jobEntity.setExecutorRouteStrategy("FIRST"); + jobEntity.setMisfireStrategy("DO_NOTHING"); + jobEntity.setExecutorTimeout("0"); + jobEntity.setExecutorFailRetryCount("0"); + jobEntity.setGlueRemark("wyl测试新建项目"); + Integer job = dynamicXxlJobService.createJob(jobEntity); + } + + @Test + void updateJobTest() { + JobEntity jobEntity = new JobEntity(); + jobEntity.setId(7); + jobEntity.setJobGroup("2"); + jobEntity.setJobDesc("测试项目"+ LocalDateTime.now()+"更新"); + jobEntity.setAuthor("wyl"); + jobEntity.setScheduleConf("* * * * * ?"); + jobEntity.setCronGenDisplay("* * * * * ?"); + jobEntity.setGlueType("BEAN"); + jobEntity.setExecutorHandler("wylDemoHandler"); + jobEntity.setExecutorRouteStrategy("FIRST"); + jobEntity.setMisfireStrategy("DO_NOTHING"); + jobEntity.setExecutorTimeout("0"); + jobEntity.setExecutorFailRetryCount("0"); + jobEntity.setGlueRemark("wyl测试新建项目"); + dynamicXxlJobService.updateJob(jobEntity); + } + + @Test + void triggerJobTest() { + JobTriggerEntity jobTriggerEntity = new JobTriggerEntity(); + jobTriggerEntity.setId(5); + jobTriggerEntity.setExecutorParam("123"); + dynamicXxlJobService.triggerJob(jobTriggerEntity); + } + + @Test + void startJobTest() { + boolean b = dynamicXxlJobService.startJob(3); + } + + @Test + void stopJobJobTest() { + boolean b = dynamicXxlJobService.stopJob(3); + } + + @Test + void removeJobTest() { + boolean b = dynamicXxlJobService.removeJob(1); } } From 7735590c7c7f37387f4dc6e5997f08c6fde79a77 Mon Sep 17 00:00:00 2001 From: wyl <959814898@qq.com> Date: Sun, 8 May 2022 22:17:42 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E5=A2=9E=E5=8A=A0spel=E9=85=8D=E5=90=88?= =?UTF-8?q?=E6=B3=A8=E8=A7=A3=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring-boot/spring-boot-common/pom.xml | 74 +++++++++++++++++++ .../common/SpringBootCommonApplication.java | 22 ++++++ .../boot/common/aop/advisor/LogAdvisor.java | 18 +++++ .../common/aop/advisor/LogAutoConfigure.java | 25 +++++++ .../common/aop/advisor/LogInterceptor.java | 23 ++++++ .../boot/common/aop/advisor/LogPointcut.java | 21 ++++++ .../boot/common/aop/annotation/LogTest.java | 10 +++ .../boot/common/aop/aspect/LogAspect.java | 65 ++++++++++++++++ .../common/bean/init/BeanInitExample.java | 33 +++++++++ .../boot/common/service/LogTestService.java | 13 ++++ .../service/impl/LogTestServiceImpl.java | 30 ++++++++ .../boot/common/spel/SpelTestAspect.java | 61 +++++++++++++++ .../boot/common/spel/annotation/SpelTest.java | 15 ++++ .../spring/boot/common/spel/bean/Order.java | 9 +++ .../spel/service/EvaluationContext.java | 22 ++++++ .../boot/common/spel/service/Evaluator.java | 52 +++++++++++++ .../boot/common/spel/service/RootObject.java | 15 ++++ .../src/main/resources/application.properties | 1 + .../SpringBootCommonApplicationTests.java | 51 +++++++++++++ .../test/java/com/wyl/example/AppTest.java | 20 ----- .../java/com/wyl/example/service/Service.java | 5 ++ .../com/wyl/example/service/ServiceTest.java | 8 ++ 22 files changed, 573 insertions(+), 20 deletions(-) create mode 100644 spring-boot/spring-boot-common/pom.xml create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/SpringBootCommonApplication.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogAdvisor.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogAutoConfigure.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogInterceptor.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogPointcut.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/annotation/LogTest.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/aspect/LogAspect.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/bean/init/BeanInitExample.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/service/LogTestService.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/service/impl/LogTestServiceImpl.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/SpelTestAspect.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/annotation/SpelTest.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/bean/Order.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/EvaluationContext.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/Evaluator.java create mode 100644 spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/RootObject.java create mode 100644 spring-boot/spring-boot-common/src/main/resources/application.properties create mode 100644 spring-boot/spring-boot-common/src/test/java/com/wyl/spring/boot/common/SpringBootCommonApplicationTests.java delete mode 100644 spring-boot/spring-boot-drools/src/test/java/com/wyl/example/AppTest.java create mode 100644 spring-boot/spring-boot-drools/src/test/java/com/wyl/example/service/Service.java create mode 100644 spring-boot/spring-boot-drools/src/test/java/com/wyl/example/service/ServiceTest.java diff --git a/spring-boot/spring-boot-common/pom.xml b/spring-boot/spring-boot-common/pom.xml new file mode 100644 index 0000000..caf3cc2 --- /dev/null +++ b/spring-boot/spring-boot-common/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + + com.wyl + spring-boot-common + 0.0.1-SNAPSHOT + spring-boot-common + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter + + + + + + + org.springframework.boot + spring-boot-starter-aop + + + org.aspectj + aspectjweaver + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework + spring-tx + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/SpringBootCommonApplication.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/SpringBootCommonApplication.java new file mode 100644 index 0000000..3106988 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/SpringBootCommonApplication.java @@ -0,0 +1,22 @@ +package com.wyl.spring.boot.common; + +import com.wyl.spring.boot.common.bean.init.BeanInitExample; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@EnableAspectJAutoProxy(exposeProxy = true) +public class SpringBootCommonApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootCommonApplication.class, args); + } + + @Bean + BeanInitExample beanInitExample() { + return new BeanInitExample(); + } +} diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogAdvisor.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogAdvisor.java new file mode 100644 index 0000000..23894c8 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogAdvisor.java @@ -0,0 +1,18 @@ +package com.wyl.spring.boot.common.aop.advisor; + +import org.springframework.aop.Pointcut; +import org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor; + +/** + * DATE 4:45 PM + * + * @author mzt. + */ +public class LogAdvisor extends AbstractBeanFactoryPointcutAdvisor { + LogPointcut logPointcut = new LogPointcut(); + + @Override + public Pointcut getPointcut() { + return logPointcut; + } +} \ No newline at end of file diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogAutoConfigure.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogAutoConfigure.java new file mode 100644 index 0000000..d929290 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogAutoConfigure.java @@ -0,0 +1,25 @@ +package com.wyl.spring.boot.common.aop.advisor; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class LogAutoConfigure { + @Bean + LogPointcut logPointcut() { + return new LogPointcut(); + } + + @Bean + LogAdvisor logAdvisor() { + LogAdvisor logAdvisor = new LogAdvisor(); + logAdvisor.setAdvice(logInterceptor()); + return logAdvisor; + } + + @Bean + LogInterceptor logInterceptor() { + return new LogInterceptor(); + } +} + diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogInterceptor.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogInterceptor.java new file mode 100644 index 0000000..d8ad2b8 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogInterceptor.java @@ -0,0 +1,23 @@ +package com.wyl.spring.boot.common.aop.advisor; + +import com.wyl.spring.boot.common.spel.service.Evaluator; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +/** + * @author: wangyl + * @date: 2022/5/1 + * @description: 再方法执行前以及执行进行代理操作 + */ +public class LogInterceptor implements MethodInterceptor { + + + private final Evaluator evaluator = new Evaluator(); + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + System.out.println("Advisor 方法执行前"); + Object proceed = invocation.proceed(); + System.out.println("Advisor 方法执行后"); + return proceed; + } +} diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogPointcut.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogPointcut.java new file mode 100644 index 0000000..e1357b7 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/advisor/LogPointcut.java @@ -0,0 +1,21 @@ +package com.wyl.spring.boot.common.aop.advisor; + +import com.wyl.spring.boot.common.aop.annotation.LogTest; +import org.springframework.aop.support.StaticMethodMatcherPointcut; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.Objects; + +/** + * @author: wangyl + * @date: 2022/4/30 + * @description: apo静态切入点,切入所有matches返回true的方法 + */ +public class LogPointcut extends StaticMethodMatcherPointcut implements Serializable { + @Override + public boolean matches(Method method, Class targetClass) { + LogTest annotation = method.getAnnotation(LogTest.class); + return !Objects.isNull(annotation); + } +} diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/annotation/LogTest.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/annotation/LogTest.java new file mode 100644 index 0000000..d35c7fe --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/annotation/LogTest.java @@ -0,0 +1,10 @@ +package com.wyl.spring.boot.common.aop.annotation; + +import java.lang.annotation.*; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Inherited//注解会被继承 +@Documented +public @interface LogTest { +} diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/aspect/LogAspect.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/aspect/LogAspect.java new file mode 100644 index 0000000..23ef6cd --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/aop/aspect/LogAspect.java @@ -0,0 +1,65 @@ +package com.wyl.spring.boot.common.aop.aspect; + +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.*; +import org.springframework.stereotype.Component; + +/** + * 接口出入参数信息依赖swagger + * + * @author wangyl + * @version V1.0 + * @ClassName: WebLogAspect + * @Date: 2022/1/5 22:58 + */ +@Aspect +@Slf4j +@Component +public class LogAspect { + + /** + * 以自定义 @WebLog 注解为切点 + */ + @Pointcut("@annotation(com.wyl.spring.boot.common.aop.annotation.LogTest)") + public void webLog() { + } + + /** + * 在切点之前织入 + * + * @param joinPoint + * @throws Throwable + */ + @Before("webLog()") + public void doBefore(JoinPoint joinPoint) { + System.out.println("Aspect Before 打印"); + } + + /** + * 在切点之后织入 + * + * @throws Throwable + */ + @After("webLog()") + public void doAfter() { + System.out.println("Aspect After 打印"); + } + + /** + * 环绕 + * + * @param proceedingJoinPoint + * @return + * @throws Throwable + */ + @Around("webLog()") + public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { + System.out.println("Aspect 方法执行前打印 打印"); + Object proceed = proceedingJoinPoint.proceed(); + System.out.println("Aspect 方法执行后打印 打印"); + return proceed; + } + +} \ No newline at end of file diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/bean/init/BeanInitExample.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/bean/init/BeanInitExample.java new file mode 100644 index 0000000..f5ba7f5 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/bean/init/BeanInitExample.java @@ -0,0 +1,33 @@ +package com.wyl.spring.boot.common.bean.init; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +public class BeanInitExample implements InitializingBean, DisposableBean { + public BeanInitExample() { + System.out.println("构造函数被调用"); + } + + @PostConstruct + public void init() { + System.out.println("PostConstruct 被调用"); + } + + @PreDestroy + public void disposable() { + System.out.println("PreDestroy 被调用"); + } + + @Override + public void afterPropertiesSet() throws Exception { + System.out.println("InitializingBean 被调用"); + } + + @Override + public void destroy() throws Exception { + System.out.println("DisposableBean 被调用"); + } +} diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/service/LogTestService.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/service/LogTestService.java new file mode 100644 index 0000000..b1782d1 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/service/LogTestService.java @@ -0,0 +1,13 @@ +package com.wyl.spring.boot.common.service; + +import com.wyl.spring.boot.common.spel.bean.Order; + +import java.util.List; + +public interface LogTestService { + void test(); + + void testSPEL(Order order); + + void testSPELList(List orders); +} diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/service/impl/LogTestServiceImpl.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/service/impl/LogTestServiceImpl.java new file mode 100644 index 0000000..67c844d --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/service/impl/LogTestServiceImpl.java @@ -0,0 +1,30 @@ +package com.wyl.spring.boot.common.service.impl; + +import com.wyl.spring.boot.common.aop.annotation.LogTest; +import com.wyl.spring.boot.common.service.LogTestService; +import com.wyl.spring.boot.common.spel.annotation.SpelTest; +import com.wyl.spring.boot.common.spel.bean.Order; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class LogTestServiceImpl implements LogTestService { + @Override + @LogTest + public void test() { + System.out.println("testLog"); + } + + + @SpelTest(spel = "{#order.id}") + public void testSPEL(Order order) { + System.out.println(123); + } + + @Override + @SpelTest(spel = "{#orders.![#this.id]}") + public void testSPELList(List orders) { + System.out.println(); + } +} diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/SpelTestAspect.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/SpelTestAspect.java new file mode 100644 index 0000000..04c318d --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/SpelTestAspect.java @@ -0,0 +1,61 @@ +package com.wyl.spring.boot.common.spel; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.wyl.spring.boot.common.spel.annotation.SpelTest; +import com.wyl.spring.boot.common.spel.service.EvaluationContext; +import com.wyl.spring.boot.common.spel.service.Evaluator; +import com.wyl.spring.boot.common.spel.service.RootObject; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.*; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.aop.framework.AopProxyUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; + +@Aspect +@Slf4j +@Component +public class SpelTestAspect { + /** + * 日志SpEL解析器 + */ + private final Evaluator evaluator = new Evaluator(); + + /** + * 日志切入点 + */ + @Pointcut(value = "@annotation(com.wyl.spring.boot.common.spel.annotation.SpelTest)") + public void SpelTestPointCut() { + } + + + @Around(value = "SpelTestPointCut()") + public Object errorLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { + proceedingJoinPoint.getArgs(); + Signature signature = proceedingJoinPoint.getSignature(); + MethodSignature methodSignature = (MethodSignature) signature; + Method method = methodSignature.getMethod(); + Object[] args = proceedingJoinPoint.getArgs(); + Class targetClass = AopProxyUtils.ultimateTargetClass(proceedingJoinPoint.getTarget()); + SpelTest annotation = method.getAnnotation(SpelTest.class); + /** + * 生成元数据 + */ + RootObject rootObject = new RootObject(); + /** + * 生成spel上下文 + */ + EvaluationContext context = new EvaluationContext(rootObject, method, args, evaluator.getDiscoverer()); + /** + * 解析spel + */ + Object content = evaluator.parse(annotation.spel(), context); + System.out.println(content); + return proceedingJoinPoint.proceed(); + } +} \ No newline at end of file diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/annotation/SpelTest.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/annotation/SpelTest.java new file mode 100644 index 0000000..3371e02 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/annotation/SpelTest.java @@ -0,0 +1,15 @@ +package com.wyl.spring.boot.common.spel.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface SpelTest { + /** + * spel + */ + String spel(); +} \ No newline at end of file diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/bean/Order.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/bean/Order.java new file mode 100644 index 0000000..a833ba6 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/bean/Order.java @@ -0,0 +1,9 @@ +package com.wyl.spring.boot.common.spel.bean; + +import lombok.Data; + +@Data +public class Order { + Integer id; + String name; +} diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/EvaluationContext.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/EvaluationContext.java new file mode 100644 index 0000000..7c76f50 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/EvaluationContext.java @@ -0,0 +1,22 @@ +package com.wyl.spring.boot.common.spel.service; + +import org.springframework.context.expression.MethodBasedEvaluationContext; +import org.springframework.core.ParameterNameDiscoverer; + +import java.lang.reflect.Method; +/** + * @author: wangyl + * @date: 2022/5/8 + * @description: 解析上下文, 用于整个解析环境 + */ +public class EvaluationContext extends MethodBasedEvaluationContext { + /** + * 构造方法 + * + * @param rootObject 数据来源对象 + * @param discoverer 参数解析器 + */ + public EvaluationContext(RootObject rootObject, Method method, Object[] arguments, ParameterNameDiscoverer discoverer) { + super(rootObject, method, arguments, discoverer); + } +} \ No newline at end of file diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/Evaluator.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/Evaluator.java new file mode 100644 index 0000000..308be3f --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/Evaluator.java @@ -0,0 +1,52 @@ +package com.wyl.spring.boot.common.spel.service; + +import lombok.Getter; +import org.springframework.core.DefaultParameterNameDiscoverer; +import org.springframework.core.ParameterNameDiscoverer; +import org.springframework.expression.Expression; +import org.springframework.expression.ParserContext; +import org.springframework.expression.common.TemplateParserContext; +import org.springframework.expression.spel.standard.SpelExpressionParser; + +/** + * @author: wangyl + * @date: 2022/5/8 + * @description: spel解析处理器 + */ +@Getter +public class Evaluator { + /** + * SpEL解析器 + */ + private final SpelExpressionParser parser = new SpelExpressionParser(); + /** + * 参数解析器 + */ + private final ParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer(); + /** + * 表达式模板 + */ + private final ParserContext template = new TemplateParserContext("{", "}"); + + /** + * 解析 + * + * @param expression 表达式 + * @param context 日志表达式上下文 + * @return 表达式结果 + */ + public Object parse(String expression, EvaluationContext context) { + return getExpression(expression).getValue(context); + } + + /** + * 获取翻译后表达式 + * + * @param expression 字符串表达式 + * @return 翻译后表达式 + */ + private Expression getExpression(String expression) { + return getParser().parseExpression(expression, template); + } + +} \ No newline at end of file diff --git a/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/RootObject.java b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/RootObject.java new file mode 100644 index 0000000..299e607 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/java/com/wyl/spring/boot/common/spel/service/RootObject.java @@ -0,0 +1,15 @@ +package com.wyl.spring.boot.common.spel.service; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * @author: wangyl + * @date: 2022/5/8 + * @description: spel解析得元数据 + */ +@Getter +@AllArgsConstructor +public class RootObject { + +} \ No newline at end of file diff --git a/spring-boot/spring-boot-common/src/main/resources/application.properties b/spring-boot/spring-boot-common/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/spring-boot/spring-boot-common/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/spring-boot/spring-boot-common/src/test/java/com/wyl/spring/boot/common/SpringBootCommonApplicationTests.java b/spring-boot/spring-boot-common/src/test/java/com/wyl/spring/boot/common/SpringBootCommonApplicationTests.java new file mode 100644 index 0000000..fa8fcad --- /dev/null +++ b/spring-boot/spring-boot-common/src/test/java/com/wyl/spring/boot/common/SpringBootCommonApplicationTests.java @@ -0,0 +1,51 @@ +package com.wyl.spring.boot.common; + +import com.wyl.spring.boot.common.service.LogTestService; +import com.wyl.spring.boot.common.spel.bean.Order; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Arrays; +import java.util.List; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) +class SpringBootCommonApplicationTests { + + @Autowired + LogTestService logTestService; + + @Test + void beanInit() { + } + + @Test + void LogTestServiceTest() { + logTestService.test(); + } + + @Test + void SpelTest() { + Order order = new Order(); + order.setId(123); + order.setName("wyl"); + logTestService.testSPEL(order); + } + + @Test + void SpelListTest() { + Order order1 = new Order(); + order1.setId(1); + order1.setName("wyl1"); + Order order2 = new Order(); + order2.setId(2); + order2.setName("wyl2"); + Order order3 = new Order(); + order3.setId(3); + order3.setName("wyl3"); + List orders = Arrays.asList(order1, order2, order3); + logTestService.testSPELList(orders); + } + + +} diff --git a/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/AppTest.java b/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/AppTest.java deleted file mode 100644 index 70b9b96..0000000 --- a/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/AppTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.wyl.example; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -/** - * Unit test for simple App. - */ -public class AppTest -{ - /** - * Rigorous Test :-) - */ - @Test - public void shouldAnswerWithTrue() - { - assertTrue( true ); - } -} diff --git a/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/service/Service.java b/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/service/Service.java new file mode 100644 index 0000000..c38dcf7 --- /dev/null +++ b/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/service/Service.java @@ -0,0 +1,5 @@ +package com.wyl.example.service; + +public interface Service { + void test(); +} diff --git a/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/service/ServiceTest.java b/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/service/ServiceTest.java new file mode 100644 index 0000000..ad08bba --- /dev/null +++ b/spring-boot/spring-boot-drools/src/test/java/com/wyl/example/service/ServiceTest.java @@ -0,0 +1,8 @@ +package com.wyl.example.service; + +public class ServiceTest implements Service{ + @Override + public void test() { + + } +}