diff --git a/build.gradle b/build.gradle index 20100a1c2941989495a80db69b792da12965d7a2..de7b85fcdcbd5ca6639dfa9796b7fc132521f727 100644 --- a/build.gradle +++ b/build.gradle @@ -20,5 +20,4 @@ allprojects { task clean(type: Delete) { delete rootProject.buildDir -} - +} \ No newline at end of file diff --git a/daydayup-algorithm/readme.md b/daydayup-algorithm/readme.md index 4d1d3580951aaa771abeb9dae9f3dca4b2eac8aa..b9c73597e8b86706badfc9fd42f178c29625d7ad 100644 --- a/daydayup-algorithm/readme.md +++ b/daydayup-algorithm/readme.md @@ -13,6 +13,7 @@ https://blog.csdn.net/wfq784967698/article/details/79551476 - [ ] 二分查找 + #### 术语说明 > - 稳定:如果a原本在b前面,而a=b,排序之后a仍然在b的前面; > - 不稳定:如果a原本在b的前面,而a=b,排序之后a可能会出现在b的后面; diff --git a/daydayup-algorithm/src/main/java/com/lecoboy/leecode/InvertedListCase.java b/daydayup-algorithm/src/main/java/com/lecoboy/leecode/InvertedListCase.java new file mode 100644 index 0000000000000000000000000000000000000000..61ac553b9a09ccc4281bce0e36b775afb6b1705b --- /dev/null +++ b/daydayup-algorithm/src/main/java/com/lecoboy/leecode/InvertedListCase.java @@ -0,0 +1,57 @@ +package com.lecoboy.leecode; + +import java.util.List; + +/** + * 链表反转 + */ +public class InvertedListCase { + class ListNode { + int data; + ListNode next; + + ListNode(int x) { + data = x; + } + + public String show() { + return this.data + "->" + (this.next == null ? "NULL" : this.next.show()); + } + } + + public static void main(String[] args) { + InvertedListCase invertedListCase = new InvertedListCase(); + ListNode a = invertedListCase.new ListNode(1); + ListNode b = invertedListCase.new ListNode(2); + ListNode c = invertedListCase.new ListNode(3); + ListNode d = invertedListCase.new ListNode(4); + + a.next = b; + b.next = c; + c.next = d; + System.out.println(a.show()); + System.out.println(invertedListCase.reverseList(a).show()); + } + + + /** + * 链表反转 + * 方法:head的循环next,对prev进行尾插法 + * @param head + * @return + */ + public ListNode reverseList(ListNode head) { + ListNode prev = null; + //尾插法 + while (head != null) { + //当前节点 + ListNode cur = head; + //头指针指向下一个, + head = head.next; + //当前节点尾结点指向当前节点,因为是尾插 + cur.next = prev; + prev = cur; + } + return prev; + } +} diff --git a/daydayup-algorithm/src/main/java/com/lecoboy/leecode/RemoveDuplicatesInts.java b/daydayup-algorithm/src/main/java/com/lecoboy/leecode/RemoveDuplicatesInts.java new file mode 100644 index 0000000000000000000000000000000000000000..678486c6547cb0875c13ce7c633ba924900587cb --- /dev/null +++ b/daydayup-algorithm/src/main/java/com/lecoboy/leecode/RemoveDuplicatesInts.java @@ -0,0 +1,49 @@ +package com.lecoboy.leecode; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class RemoveDuplicatesInts { + public static void main(String[] args) { + int[] i = new int[]{0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; + System.out.println("总条数" + removeDuplicates(i)); + } + + public int removeDuplicates(int[] nums) { + if (nums.length == 0) return 0; + Set set = new HashSet<>(); + for (int j = 0; j < nums.length; j++) { + set.add(nums[j]); + } + return set.size(); + } + + private static void printNums(int[] nums) { + System.out.println("---"); + for (int i : nums) { + System.out.printf(i + ","); + } + + } + + public static int removeDuplicates2(int[] nums) { + if (nums.length == 0) { + return 0; + } + //慢指针,用于存放相同key的索引位置 + int i = 0; + //定义j从第2个开始起始,不断和i指针数据对比 + //如果不相等则向下移动对比值指针 + //并且把对比的下一个数据挪到对比指针下一个指针位置即nums[i],后面就可以继续使用nums[i]进行对比 + for (int j = 1; j < nums.length; j++) { + if (nums[j] != nums[i]) { + i++; + nums[i] = nums[j]; + } + } + //因为从第一位起就应该算一个不重复数据 + return i + 1; + } +} diff --git a/daydayup-algorithm/src/main/java/com/lecoboy/leecode/readme.md b/daydayup-algorithm/src/main/java/com/lecoboy/leecode/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..09225b0606c83792e172964e93da35ba4b5cacb5 --- /dev/null +++ b/daydayup-algorithm/src/main/java/com/lecoboy/leecode/readme.md @@ -0,0 +1,3 @@ +#Leecode + +#### [链表反转](InvertedListCase.java) \ No newline at end of file diff --git a/daydayup-design-patterns/build.gradle b/daydayup-design-patterns/build.gradle index b7e4b990040153cc601bc6023bd00a2284325c32..dc0819cf5a3fd428bdaadbf9d557295fa8774262 100644 --- a/daydayup-design-patterns/build.gradle +++ b/daydayup-design-patterns/build.gradle @@ -25,4 +25,8 @@ repositories { dependencies { implementation 'org.springframework.boot:spring-boot-starter' testImplementation 'org.springframework.boot:spring-boot-starter-test' + compile 'junit:junit:4.12' + // https://mvnrepository.com/artifact/org.projectlombok/lombok + compile group: 'org.projectlombok', name: 'lombok', version: '1.18.12' + } diff --git a/daydayup-design-patterns/readme.md b/daydayup-design-patterns/readme.md index 250086c1db556d178666afd00e2c8451706b8088..51a1672dd4d5725e955fd4795dbb9cf318b9a241 100644 --- a/daydayup-design-patterns/readme.md +++ b/daydayup-design-patterns/readme.md @@ -1,3 +1,5 @@ +# 架构设计七大原则 + # 设计模式 ##### 常用23种设计模式 `design_patterns` diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/DipTest.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/DipTest.java new file mode 100644 index 0000000000000000000000000000000000000000..86f86a40d9357d699cb6fb8be834c71c360a21f5 --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/DipTest.java @@ -0,0 +1,39 @@ +package com.lecoboy.gupaoclass.principle.dependencyinversion; + +/** + * 依赖倒置原则 + * + * 高层模块 + * 不应该依赖低层,而是应该其抽象 + * 底层写过后,一般不会变,改变的在高层 + * 面向抽象编程 + */ +public class DipTest { + public static void main(String[] args) { + //---------v1 面向实现编程---------- + /* Tom tom = new Tom(); + tom.studyAiCourse(); + tom.studyJavaCourse(); + tom.studyPythonCourse();*/ + + //---------v2 注入方式实现依赖倒置--------- + // 符合开闭原则,Spring中常见,即依赖注入 + /* Tom tom = new Tom(); + tom.study(new JavaCourse()); + tom.study(new PythonCourse());*/ + + //---------v3 构造方法实现依赖倒置--------- + /* Tom tom = new Tom(new JavaCourse()); + tom.study(); +*/ + + //---------v4 构造方法的升级版 在Tom单例时多设置--------- + Tom tom = new Tom(); + tom.setCourse(new JavaCourse()); + tom.study(); + + tom.setCourse(new PythonCourse()); + tom.study(); + + } +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/ICourse.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/ICourse.java new file mode 100644 index 0000000000000000000000000000000000000000..65b8963c9c3e04d682e84aadd252860852b692a1 --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/ICourse.java @@ -0,0 +1,10 @@ +package com.lecoboy.gupaoclass.principle.dependencyinversion; + +/** + * + * 课程抽象方法 + * 面向接口编程 + */ +public interface ICourse { + void study(); +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/JavaCourse.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/JavaCourse.java new file mode 100644 index 0000000000000000000000000000000000000000..7fb1d94b6a8d6c93c51cd18074eaae75437855b2 --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/JavaCourse.java @@ -0,0 +1,12 @@ +package com.lecoboy.gupaoclass.principle.dependencyinversion; + +/** + * Java抽象类 + */ +public class JavaCourse implements ICourse { + + @Override + public void study() { + System.out.println("Tom正在学习java"); + } +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/PythonCourse.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/PythonCourse.java new file mode 100644 index 0000000000000000000000000000000000000000..4e7362be0dbcaf64657cece87e3ac2ea2d9e7f0c --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/PythonCourse.java @@ -0,0 +1,11 @@ +package com.lecoboy.gupaoclass.principle.dependencyinversion; + +/** + * python抽象类 + */ +public class PythonCourse implements ICourse { + @Override + public void study() { + System.out.println("Tom正在学习Python"); + } +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/Tom.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/Tom.java new file mode 100644 index 0000000000000000000000000000000000000000..37134bc0d3615b58f1bf5ec1d3665579c15d93bc --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/dependencyinversion/Tom.java @@ -0,0 +1,50 @@ +package com.lecoboy.gupaoclass.principle.dependencyinversion; + +public class Tom { + /* + -------v1------ + public void studyJavaCourse() { + System.out.println("Tom正在学习java"); + } + + public void studyPythonCourse() { + System.out.println("Tom正在学习Python"); + } + + public void studyAiCourse() { + System.out.println("Tom正在学习Ai"); + }*/ + + + /*-------v2------*/ + /* */ + /** + * 符合开闭原则的 Tom的学习方法,其他的不需要关心 + * + * @param iCourse 抽象的类 + *//* + public void study(ICourse iCourse){ + iCourse.study(); + }*/ + /*-------v3 构造设置值------*/ + /*private ICourse iCourse; + + public Tom(ICourse iCourse) { + this.iCourse = iCourse; + } + + public void study() { + iCourse.study(); + }*/ + + /*-------v4 单例时可重新set值------*/ + private ICourse iCourse; + + public void setCourse(ICourse iCourse) { + this.iCourse = iCourse; + } + + public void study() { + iCourse.study(); + } +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/ICourse.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/ICourse.java new file mode 100644 index 0000000000000000000000000000000000000000..e28f941aecb4ae5d7d40a8ec7de713cdc04fc392 --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/ICourse.java @@ -0,0 +1,12 @@ +package com.lecoboy.gupaoclass.principle.openclose; + +/** + * 课程接口 面向接口编程 + */ +public interface ICourse { + Integer getId(); + + String getName(); + + Double getPrice(); +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/JavaCourse.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/JavaCourse.java new file mode 100644 index 0000000000000000000000000000000000000000..6a7f22ad21adb27a01f23cd41daf282612d454d1 --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/JavaCourse.java @@ -0,0 +1,29 @@ +package com.lecoboy.gupaoclass.principle.openclose; + +/** + * 课程类 + */ +public class JavaCourse implements ICourse { + private Integer id; + private String name; + private Double price; + + public JavaCourse(Integer id, String name, Double price) { + this.id = id; + this.name = name; + this.price = price; + } + + @Override + public Integer getId() { + return id; + } + @Override + public String getName() { + return name; + } + @Override + public Double getPrice() { + return price; + } +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/JavaDiscountCourse.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/JavaDiscountCourse.java new file mode 100644 index 0000000000000000000000000000000000000000..a96ec12018c6bb7b4511df8c49a5149ae9e5f9ea --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/JavaDiscountCourse.java @@ -0,0 +1,19 @@ +package com.lecoboy.gupaoclass.principle.openclose; + +/** + * 打折类 + */ +public class JavaDiscountCourse extends JavaCourse { + public JavaDiscountCourse(Integer id, String name, Double price) { + super(id, name, price); + } + + /** + * 打折价格 里氏替换原则 + * @return + */ + public Double getDiscountPrice() { + //打八折 + return super.getPrice() * 0.8; + } +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/OpenCloseTest.java b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/OpenCloseTest.java new file mode 100644 index 0000000000000000000000000000000000000000..73aa74dc6b2ae91cf22ae080163e00a6f0f8f98c --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/openclose/OpenCloseTest.java @@ -0,0 +1,16 @@ +package com.lecoboy.gupaoclass.principle.openclose; + + +/** + * 开闭原则 + */ +public class OpenCloseTest { + public static void main(String[] args) { + ICourse iCourse = new JavaDiscountCourse(1, "《Java架构师》", 18000D); + JavaDiscountCourse discountCourse = (JavaDiscountCourse) iCourse; + System.out.println("Id:" + discountCourse.getId() + + "\n 课程名称:" + discountCourse.getName() + + "\n 折后价格:" + discountCourse.getDiscountPrice() + + "\n 售价:" + discountCourse.getPrice()); + } +} diff --git a/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/readme.md b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..b6059dffed636c5374cdc1702dcae88964eb055c --- /dev/null +++ b/daydayup-design-patterns/src/main/java/com/lecoboy/gupaoclass/principle/readme.md @@ -0,0 +1,3 @@ +# 架构设计七大原则 +## 1、[开闭原则](openclose/OpenCloseTest.java) +## 2、[依赖倒置原则](dependencyinversion/DipTest.java) diff --git a/daydayup-high-concurrency/build.gradle b/daydayup-high-concurrency/build.gradle index b7e4b990040153cc601bc6023bd00a2284325c32..fe8932ba21abc517835853abe0e790fa016e2db2 100644 --- a/daydayup-high-concurrency/build.gradle +++ b/daydayup-high-concurrency/build.gradle @@ -23,6 +23,9 @@ repositories { } dependencies { + implementation 'org.springframework.boot:spring-boot-starter' - testImplementation 'org.springframework.boot:spring-boot-starter-test' + compile 'org.springframework.boot:spring-boot-starter-test' + compile 'redis.clients:jedis:2.9.0' + compile 'junit:junit:4.12' } diff --git a/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/JedisUtil.java b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/JedisUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..639d243d51249f98f9adc5caef01209642d877c1 --- /dev/null +++ b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/JedisUtil.java @@ -0,0 +1,12 @@ +package com.lecoboy.redisdistributedlock; + +import org.springframework.stereotype.Service; +import redis.clients.jedis.Jedis; + +@Service +public class JedisUtil { + public static Jedis getJedis(){ + Jedis jedis = new Jedis("10.32.16.22"); + return jedis; + } +} diff --git a/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/RedisLockImpl.java b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/RedisLockImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..ce4c430b695dc41cbf49e54bf8bf16253ff5762c --- /dev/null +++ b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/RedisLockImpl.java @@ -0,0 +1,152 @@ +package com.lecoboy.redisdistributedlock; + +import org.springframework.stereotype.Service; +import redis.clients.jedis.Jedis; + +import java.util.Collections; +import java.util.UUID; +import java.util.concurrent.*; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; + +@Service +public class RedisLockImpl implements Lock { + //要锁的key + private final String redis_key = "KEY"; + //超时时长 + private final int redis_time = 3; + //订阅通道,当释放锁后进行通知阻塞中的线程 + private final String REDIS_CHANNEL_NAME = "redis_channel_name"; + //线程传值使用 + private static ThreadLocal threadLocal = new ThreadLocal<>(); + //线程池控制 + ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3); + //锁续命使用,定时监控线程情况 + private static ConcurrentHashMap futures = new ConcurrentHashMap<>(); + + @Override + public void lock() { + //1.尝试加锁 + if (tryLock()) { + return; + } + String uuid = threadLocal.get(); + CountDownLatch cdl = new CountDownLatch(1);//线程协调 + Subscriber subscriber = new Subscriber(cdl, Thread.currentThread());//定义订阅对象 + Jedis jedis = JedisUtil.getJedis(); + + new Thread(new Runnable() { + @Override + public void run() { + jedis.subscribe(subscriber, REDIS_CHANNEL_NAME); + } + }).start(); + //printLog("开始订阅"); + try { + cdl.await();//阻塞等待解锁 + //printLog("开始抢夺锁"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //取消订阅 + subscriber.unsubscribe(REDIS_CHANNEL_NAME); + //重复 + lock(); + } + + private void setHeartBeat(String uuid) { + //如果有心跳检测则直接返回 + if (futures.contains(uuid)) { + printLog("已经有心跳了"); + return; + } + Thread thread = Thread.currentThread(); + //20s启动一个任务去心跳 + Future future = scheduledExecutorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + Jedis jedis = JedisUtil.getJedis(); + System.out.println(thread.getName() + "心跳检测"); + if (jedis.get(redis_key).equals(uuid)) { + //任务存在,说明任务健康,但快到失效时间,则续命 + //续命 + System.out.println(thread.getName() + "锁续命 +3s"); + jedis.expire(redis_key, redis_time); + } else { + System.out.println(thread.getName() + "锁已释放"); + + //任务节点不存在,咋说明锁已经释放,调度任务取消 + futures.get(uuid).cancel(true); + futures.remove(uuid); + } + jedis.close(); + } + }, 1, redis_time-1, TimeUnit.SECONDS); + //printLog("启动心跳"); + futures.put(uuid, future); + } + + @Override + public void lockInterruptibly() throws InterruptedException { + + } + + @Override + public boolean tryLock() { + threadLocal.set(null); + //printLog("尝试获取锁"); + String uuid = UUID.randomUUID().toString(); + Jedis jedis = JedisUtil.getJedis(); + String ret = jedis.set(redis_key, uuid, "NX", "PX", redis_time * 1000); + if ("OK".equals(ret)) { + threadLocal.set(uuid); + printLog("获得锁成功"); + //开启心跳 + setHeartBeat(uuid); + jedis.close(); + //加锁成功 + return true; + } + jedis.close(); + return false; + } + + @Override + public void unlock() { + String uuid = threadLocal.get(); + printLog("开始解锁"); + + String luaScript = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" + + " return redis.call(\"del\",KEYS[1])\n" + + "else\n" + + " return 0\n" + + "end"; + Jedis jedis = JedisUtil.getJedis(); + //执行lua脚本 KEYS ARGV 两个参数 + jedis.eval(luaScript, Collections.singletonList(redis_key), Collections.singletonList(uuid)); + //解锁时停止心跳 + Future future = futures.get(uuid); + future.cancel(true); + futures.remove(uuid); + //解锁后发送广播通知阻塞中的线程 + jedis.publish(REDIS_CHANNEL_NAME, "unlock"); + printLog("发送释放锁广播"); + jedis.close(); + } + + private void printLog(String name) { + System.out.println(Thread.currentThread().getName() + name + (threadLocal.get() == null ? "" : threadLocal.get())); + } + + @Override + public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { + return false; + } + + @Override + public Condition newCondition() { + return null; + } + + +} diff --git a/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/RedisLockTest.java b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/RedisLockTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a8612793e45275d827338a44831c1b8314803b23 --- /dev/null +++ b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/RedisLockTest.java @@ -0,0 +1,56 @@ +package com.lecoboy.redisdistributedlock; + +import org.junit.Test; + +import javax.annotation.Resource; +import java.util.concurrent.locks.Lock; + +public class RedisLockTest { + +// @Resource +// private static Lock lock; + + private static int count = 10; + + public static void main(String[] args) throws InterruptedException { + + RedisLockThread rt = new RedisLockThread(); + Thread a = new Thread(rt, "【售票员A】"); + Thread b = new Thread(rt, "【售票员B】"); + Thread c = new Thread(rt, "【售票员C】"); + Thread d = new Thread(rt, "【售票员D】"); + a.start(); + b.start(); + c.start(); + d.start(); + Thread.currentThread().join(); + } + + @Test + public void test() throws InterruptedException { + + } + + public static class RedisLockThread implements Runnable { + + @Override + public void run() { + final Lock lock = new RedisLockImpl(); + while (count > 0) { + lock.lock(); + try { + if (count > 0) { + Thread.sleep(5000); + System.out.println(Thread.currentThread().getName() + "售出第:" + (count--) + "张票"); + } else { + System.out.println(Thread.currentThread().getName() + "已经没有票了"); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + lock.unlock(); + } + } + } + } +} diff --git a/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/Subscriber.java b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/Subscriber.java new file mode 100644 index 0000000000000000000000000000000000000000..e155f8cb681d54ce54d764fc72b26719d6fdd388 --- /dev/null +++ b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/Subscriber.java @@ -0,0 +1,24 @@ +package com.lecoboy.redisdistributedlock; + +import redis.clients.jedis.JedisPubSub; + +import java.util.concurrent.CountDownLatch; + +public class Subscriber extends JedisPubSub { + private CountDownLatch countDownLatch; + private Thread thread; + + public Subscriber(CountDownLatch countDownLatch, Thread thread) { + this.countDownLatch = countDownLatch; + this.thread = thread; + } + + //监听收到消息 + //取得订阅消息后,通过countDownLatch唤醒被阻塞的线程,再次尝试获得锁 + @Override + public void onMessage(String channel, String message) { + //收到广播 + System.out.println(thread.getName() + "收到广播" + message); + countDownLatch.countDown(); + } +} diff --git a/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/unLock.lua b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/unLock.lua new file mode 100644 index 0000000000000000000000000000000000000000..5e8d8314bb65b41f3eb8c5295590a51d5f97693c --- /dev/null +++ b/daydayup-high-concurrency/src/main/java/com/lecoboy/redisdistributedlock/unLock.lua @@ -0,0 +1,5 @@ +if redis.call("get",KEYS[1]) == ARGV[1] then + return redis.call("del",KEYS[1]) +else + return 0 +end \ No newline at end of file diff --git a/daydayup-mysql/index.md b/daydayup-mysql/index.md deleted file mode 100644 index ca15e43d92231035417328ee193c14b795d50453..0000000000000000000000000000000000000000 --- a/daydayup-mysql/index.md +++ /dev/null @@ -1 +0,0 @@ -#### 索引 \ No newline at end of file diff --git a/daydayup-shardingdb/.gitignore b/daydayup-shardingdb/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6c0187813872b085601abdf653cd52410f9f3836 --- /dev/null +++ b/daydayup-shardingdb/.gitignore @@ -0,0 +1,32 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/daydayup-shardingdb/build.gradle b/daydayup-shardingdb/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..7f62cf60799b2cd677b4c64d7446af57343bf616 --- /dev/null +++ b/daydayup-shardingdb/build.gradle @@ -0,0 +1,32 @@ +buildscript { + ext { + springBootVersion = '2.1.2.RELEASE' + } + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") + } +} + +apply plugin: 'java' +apply plugin: 'org.springframework.boot' +apply plugin: 'io.spring.dependency-management' + +group = 'com.lecoboy' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '1.8' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + compile 'org.apache.rocketmq:rocketmq-client:4.1.0-incubating' +// https://mvnrepository.com/artifact/org.mybatis/mybatis + compile group: 'org.mybatis', name: 'mybatis', version: '3.5.4' + compile 'org.apache.shardingsphere:sharding-jdbc-spring-boot-starter:4.0.0-RC1' +} diff --git a/daydayup-shardingdb/settings.gradle b/daydayup-shardingdb/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..302f96c76ee1af9aa17505accd632be7d662fd2c --- /dev/null +++ b/daydayup-shardingdb/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'daydayup-shardingdb' diff --git a/daydayup-shardingdb/src/main/java/com/lecoboy/daydayupshardingdb/Application.java b/daydayup-shardingdb/src/main/java/com/lecoboy/daydayupshardingdb/Application.java new file mode 100644 index 0000000000000000000000000000000000000000..449ba62d373850fc547203c4178941d560425bbf --- /dev/null +++ b/daydayup-shardingdb/src/main/java/com/lecoboy/daydayupshardingdb/Application.java @@ -0,0 +1,13 @@ +package com.lecoboy.daydayupshardingdb; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/daydayup-shardingdb/src/main/resources/application.properties b/daydayup-shardingdb/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..18d1bddae8dbc0dcfd72e39cc53f3759b114dbe7 --- /dev/null +++ b/daydayup-shardingdb/src/main/resources/application.properties @@ -0,0 +1,31 @@ + +# 分库分表 +# 数据库 +spring.shardingsphere.datasource.names = ds0,ds1 + +# ds0 数据库连接 +spring.shardingsphere.datasource.ds0.type = com.alibaba.druid.pool.DruidDataSource +spring.shardingsphere.datasource.ds0.driver-class-name = com.mysql.jdbc.Driver +spring.shardingsphere.datasource.ds0.url = jdbc:mysql://localhost:3306/ds0 +spring.shardingsphere.datasource.ds0.username = root +spring.shardingsphere.datasource.ds0.password = +# ds1 数据库连接 +spring.shardingsphere.datasource.ds1.type = com.alibaba.druid.pool.DruidDataSource +spring.shardingsphere.datasource.ds1.driver-class-name = com.mysql.jdbc.Driver +spring.shardingsphere.datasource.ds1.url = jdbc:mysql://localhost:3306/ds1 +spring.shardingsphere.datasource.ds1.username = root +spring.shardingsphere.datasource.ds1.password = + +# 数据库分片策略 +spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id +spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=ds$->{user_id % 2} + +# 分表t_order分片策略 +spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order$->{0..1} +spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id +spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order$->{order_id % 2} + +# 分表t_order_item分片策略 +spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=ds$->{0..1}.t_order_item$->{0..1} +spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id +spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item$->{order_id % 2} \ No newline at end of file diff --git a/daydayup-shardingdb/src/test/java/com/lecoboy/daydayupshardingdb/Test.java b/daydayup-shardingdb/src/test/java/com/lecoboy/daydayupshardingdb/Test.java new file mode 100644 index 0000000000000000000000000000000000000000..38860d930390088515cbd7e3a38f620ac62bc3bb --- /dev/null +++ b/daydayup-shardingdb/src/test/java/com/lecoboy/daydayupshardingdb/Test.java @@ -0,0 +1,4 @@ +package com.lecoboy.daydayupshardingdb; + +public class Test { +} diff --git a/handwritespring/.gitignore b/handwritespring/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a2a3040aa86debfd8826d9c2b5c816314c17d9fe --- /dev/null +++ b/handwritespring/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### 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/ + +### VS Code ### +.vscode/ diff --git a/handwritespring/.mvn/wrapper/MavenWrapperDownloader.java b/handwritespring/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000000000000000000000000000000000..74f4de40122aca522184d5b1aac4f0ac29888b1a --- /dev/null +++ b/handwritespring/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.5"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/handwritespring/.mvn/wrapper/maven-wrapper.jar b/handwritespring/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..0d5e649888a4843c1520054d9672f80c62ebbb48 Binary files /dev/null and b/handwritespring/.mvn/wrapper/maven-wrapper.jar differ diff --git a/handwritespring/.mvn/wrapper/maven-wrapper.properties b/handwritespring/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..7d59a01f2594defa27705a493da0e4d57465aa2d --- /dev/null +++ b/handwritespring/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.2/apache-maven-3.6.2-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar diff --git a/handwritespring/mvnw b/handwritespring/mvnw new file mode 100755 index 0000000000000000000000000000000000000000..21d3ee84568ff68c4712677da7c3b06f61ab5543 --- /dev/null +++ b/handwritespring/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/handwritespring/mvnw.cmd b/handwritespring/mvnw.cmd new file mode 100644 index 0000000000000000000000000000000000000000..84d60abc339b13f80f3300b00387f2d4cc4eb328 --- /dev/null +++ b/handwritespring/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/handwritespring/pom.xml b/handwritespring/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..93a02e6724550b7009e3b2f51d49093df989e1eb --- /dev/null +++ b/handwritespring/pom.xml @@ -0,0 +1,180 @@ + + + 4.0.0 + + com.lecoboy + handwritespring + 0.0.1-SNAPSHOT + handwritespring + Demo project for Spring Boot + + + 1.8 + + + + + + + org.projectlombok + lombok + true + 1.18.10 + + + javax.servlet + javax.servlet-api + 4.0.1 + + + + + + ${artifactId} + + + ${basedir}/src/main/resources + + **/* + + + + ${basedir}/src/main/java + + **/*.java + **/*.class + + + + + + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + UTF-8 + + + ${java.home}/lib/rt.jar + + + + + + org.mortbay.jetty + maven-jetty-plugin + 6.1.26 + + src/main/resources/webdefault.xml + / + + + 80 + + + 0 + + + src/main/webapp + + **/*.xml + **/*.properties + + + + + + + javax.xml.parsers.DocumentBuilderFactory + + + com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl + + + + + javax.xml.parsers.SAXParserFactory + + + com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl + + + + + javax.xml.transform.TransformerFactory + + + com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl + + + + org.eclipse.jetty.util.URI.charset + UTF-8 + + + + + + + org.apache.maven.plugins + maven-war-plugin + 2.2 + + + false + + + + + src/main/resources/ + WEB-INF/classes + + **/*.* + + true + + + + src/main/resources + WEB-INF/classes + true + + + + + + org.zeroturnaround + javarebel-maven-plugin + + + generate-rebel-xml + process-resources + + generate + + + + 1.0.5 + + + + + + diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/.DS_Store b/handwritespring/src/main/java/com/lecoboy/handwritespring/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..e8a3178cf18787590df450bfdb6aff9061aacd3b Binary files /dev/null and b/handwritespring/src/main/java/com/lecoboy/handwritespring/.DS_Store differ diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/HandwritespringApplication.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/HandwritespringApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..18fa4a862371e99124f878fa9d8931ec2e1d3059 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/HandwritespringApplication.java @@ -0,0 +1,15 @@ +package com.lecoboy.handwritespring; +/* + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HandwritespringApplication { + + public static void main(String[] args) { + SpringApplication.run(HandwritespringApplication.class, args); + } + +} +*/ diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/controller/DemoController.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/controller/DemoController.java new file mode 100644 index 0000000000000000000000000000000000000000..e8b51afdcfa19089f7b5a4c3a6fb3f4fe880f738 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/controller/DemoController.java @@ -0,0 +1,19 @@ +package com.lecoboy.handwritespring.demo.controller; + +import com.lecoboy.handwritespring.demo.services.IDemoService; +import com.lecoboy.handwritespring.spring.framework.annotation.MyAutoWirted; +import com.lecoboy.handwritespring.spring.framework.annotation.MyController; +import com.lecoboy.handwritespring.spring.framework.annotation.MyRequestMapping; +import com.lecoboy.handwritespring.spring.framework.annotation.MyRequestParam; + +@MyController +@MyRequestMapping("/demo") +public class DemoController { + @MyAutoWirted + private IDemoService demoServices; + + @MyRequestMapping("/test") + public String testUrl(@MyRequestParam(value = "name") String name, @MyRequestParam(value = "id") String id) { + return demoServices.test(name, id); + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/services/IDemoService.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/services/IDemoService.java new file mode 100644 index 0000000000000000000000000000000000000000..001d61e0a80e8a402ccff9809f530f69a8ff91f5 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/services/IDemoService.java @@ -0,0 +1,5 @@ +package com.lecoboy.handwritespring.demo.services; + +public interface IDemoService { + String test(String name, String id); +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/services/impl/DemoService.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/services/impl/DemoService.java new file mode 100644 index 0000000000000000000000000000000000000000..739fa9f199bfddcdc0460387e69ac7ce54dcfc5d --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/demo/services/impl/DemoService.java @@ -0,0 +1,14 @@ +package com.lecoboy.handwritespring.demo.services.impl; + +import com.lecoboy.handwritespring.demo.services.IDemoService; +import com.lecoboy.handwritespring.spring.framework.annotation.MyServices; + +@MyServices +public class DemoService implements IDemoService { + + @Override + public String test(String name, String id) { + System.out.printf("call success"); + return String.format("name:%s,id:%s welcome to hand write spring.", name, id); + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyAutoWirted.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyAutoWirted.java new file mode 100644 index 0000000000000000000000000000000000000000..e63bc9464bb3154cfa42d8498df0d6a5676c8094 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyAutoWirted.java @@ -0,0 +1,15 @@ +package com.lecoboy.handwritespring.spring.framework.annotation; + +import java.lang.annotation.*; + +/** + * 自动注入 + * + * @author leon + */ +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface MyAutoWirted { + String value() default ""; +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyController.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyController.java new file mode 100644 index 0000000000000000000000000000000000000000..e3258c728a382223f763754f394470ae1e7df9d5 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyController.java @@ -0,0 +1,15 @@ +package com.lecoboy.handwritespring.spring.framework.annotation; + + +import java.lang.annotation.*; + +/** + * 页面交互 + * @author leon + */ +@Target({ElementType.TYPE}) //TYPE 类或接口 +@Retention(RetentionPolicy.RUNTIME) //保留类型 +@Documented +public @interface MyController { + String value() default ""; +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyRequestMapping.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyRequestMapping.java new file mode 100644 index 0000000000000000000000000000000000000000..28284f4edd9d847fc845ba49e518d73a3b53b90b --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyRequestMapping.java @@ -0,0 +1,13 @@ +package com.lecoboy.handwritespring.spring.framework.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** + * 请求url + * @author leon + */ +@Target({ElementType.TYPE,ElementType.METHOD}) +public @interface MyRequestMapping { + String value() default ""; +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyRequestParam.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyRequestParam.java new file mode 100644 index 0000000000000000000000000000000000000000..40ca96a39f52280401085ef7d0b9c1c433f4d4e8 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyRequestParam.java @@ -0,0 +1,18 @@ +package com.lecoboy.handwritespring.spring.framework.annotation; + + +import java.lang.annotation.*; + +/** + * 参数映射 + * @author leon + */ +@Target({ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface MyRequestParam { + + String value() default ""; + + boolean required() default true; +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyServices.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyServices.java new file mode 100644 index 0000000000000000000000000000000000000000..d8e12f82713e6bece0c958bd9d27ce15ea77f8fb --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/annotation/MyServices.java @@ -0,0 +1,17 @@ +package com.lecoboy.handwritespring.spring.framework.annotation; + + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 业务逻辑,注入接口 + * @author leon + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface MyServices { + String value() default ""; +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/MyBeanWrapper.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/MyBeanWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..e2eed1933080927faeda68583a1886c84badc3fd --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/MyBeanWrapper.java @@ -0,0 +1,26 @@ +package com.lecoboy.handwritespring.spring.framework.beans; + +/** + * Bean包装类 + * @author leon + */ +public class MyBeanWrapper { + + //Bean实例化的真实对象 + private Object wrapperInstance; + private Class wrapperClass; + + public MyBeanWrapper(Object wrapperInstance) { + this.wrapperInstance = wrapperInstance; + this.wrapperClass = wrapperInstance.getClass(); + } + + public Object getWrapperInstance() { + return wrapperInstance; + } + + public Class getWrapperClass() { + return wrapperClass; + } + +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/config/MyBeanDefinition.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/config/MyBeanDefinition.java new file mode 100644 index 0000000000000000000000000000000000000000..c3d7a16247ee1e511bdd85662d6f8a84d98db71c --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/config/MyBeanDefinition.java @@ -0,0 +1,28 @@ +package com.lecoboy.handwritespring.spring.framework.beans.config; + +/** + * Bean定义实体 + * @author leon + */ +public class MyBeanDefinition { + + private String factoryBeanName; + + private String beanClassName; + + public String getFactoryBeanName() { + return factoryBeanName; + } + + public void setFactoryBeanName(String factoryBeanName) { + this.factoryBeanName = factoryBeanName; + } + + public String getBeanClassName() { + return beanClassName; + } + + public void setBeanClassName(String beanClassName) { + this.beanClassName = beanClassName; + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/support/MyBeanDefinitionReader.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/support/MyBeanDefinitionReader.java new file mode 100644 index 0000000000000000000000000000000000000000..901c96880abed8c333b2e16e9e569a4fad2b7220 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/beans/support/MyBeanDefinitionReader.java @@ -0,0 +1,125 @@ +package com.lecoboy.handwritespring.spring.framework.beans.support; + +import com.lecoboy.handwritespring.spring.framework.beans.config.MyBeanDefinition; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +/** + * 加载 Bean + * + * @author Peter + */ +public class MyBeanDefinitionReader { + + private List registryBeanClasses = new ArrayList(); + + private Properties contextConfig = new Properties(); + + public MyBeanDefinitionReader(String[] configLocations) { + //直接从类路径下找到Spring主配置文件所在的路径 + //并且将其读取出来放到Properties对象中 + //相对于scanPackage=com.gupaoedu.demo 从文件中保存到了内存中 + InputStream is = this.getClass().getClassLoader().getResourceAsStream(configLocations[0].replaceAll("classpath:", "")); + try { + contextConfig.load(is); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (null != is) { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + doScanner(contextConfig.getProperty("scanPackage")); + } + + /** + * 扫描class文件,存入className + * + * @param scanPackage + */ + //扫描出相关的类 + private void doScanner(String scanPackage) { + URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/")); + //scanPackage = com.gupaoedu.demo ,存储的是包路径 + //转换为文件路径,实际上就是把.替换为/就OK了 + //classpath下不仅有.class文件, .xml文件 .properties文件 + File classPath = new File(url.getFile()); + + for (File file : classPath.listFiles()) { + + if (file.isDirectory()) { + doScanner(scanPackage + "." + file.getName()); + } else { + //变成包名.类名 + //Class.forname() + if (!file.getName().endsWith(".class")) { + continue; + } + String className = scanPackage + "." + file.getName().replace(".class", ""); + registryBeanClasses.add(className); + } + } + } + + public List loadBeanDefinitions() { + List result = new ArrayList<>(); + try { + for (String className : registryBeanClasses) { + Class beanClass = Class.forName(className); + //接口类型不需要加载 + if (beanClass.isInterface()) { + continue; + } + //1、默认类名首字母小写 + //2、自定义名字 + result.add(doCreateBeanDefinition(toLowerFirstCase(beanClass.getSimpleName()), beanClass.getName())); + + //3、接口注入 + for (Class i : beanClass.getInterfaces()) { + result.add(doCreateBeanDefinition(i.getName(), beanClass.getName())); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + + public Properties getConfig() { + return this.contextConfig; + } + + private MyBeanDefinition doCreateBeanDefinition(String fatoryBeanName, String beanClassName) { + MyBeanDefinition beanDefinition = new MyBeanDefinition(); + beanDefinition.setBeanClassName(beanClassName); + beanDefinition.setFactoryBeanName(fatoryBeanName); + return beanDefinition; + } + + //如果类名本身是小写字母,确实会出问题 + //但是我要说明的是:这个方法是我自己用,private的 + //传值也是自己传,类也都遵循了驼峰命名法 + //默认传入的值,存在首字母小写的情况,也不可能出现非字母的情况 + + //为了简化程序逻辑,就不做其他判断了,大家了解就OK + //其实用写注释的时间都能够把逻辑写完了 + private String toLowerFirstCase(String simpleName) { + char[] chars = simpleName.toCharArray(); + //之所以加,是因为大小写字母的ASCII码相差32, + // 而且大写字母的ASCII码要小于小写字母的ASCII码 + //在Java中,对char做算学运算,实际上就是对ASCII码做算学运算 + chars[0] += 32; + return String.valueOf(chars); + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/context/MyApplicationContext.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/context/MyApplicationContext.java new file mode 100644 index 0000000000000000000000000000000000000000..7a07209e824c60c339736700b82bebf555c078d6 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/context/MyApplicationContext.java @@ -0,0 +1,176 @@ +package com.lecoboy.handwritespring.spring.framework.context; + +import com.lecoboy.handwritespring.spring.framework.annotation.MyAutoWirted; +import com.lecoboy.handwritespring.spring.framework.annotation.MyController; +import com.lecoboy.handwritespring.spring.framework.annotation.MyServices; +import com.lecoboy.handwritespring.spring.framework.beans.MyBeanWrapper; +import com.lecoboy.handwritespring.spring.framework.beans.config.MyBeanDefinition; +import com.lecoboy.handwritespring.spring.framework.beans.support.MyBeanDefinitionReader; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * + */ +public class MyApplicationContext { + + private final Map beanDefinitionMap = new HashMap(); + //真实IOC容器 + private final Map factoryBeanInstanceCache = new HashMap(); + private final Map factoryBeanObjectCache = new HashMap(); + private String[] configLocations; + + private MyBeanDefinitionReader reader; + + public MyApplicationContext(String... configLocations) { + try { + + //拿配置 + this.configLocations = configLocations; + //1.读取配置 + reader = new MyBeanDefinitionReader(this.configLocations); + //2.解析配置文件,封装成BeanDefinition + List beanDefinitions = reader.loadBeanDefinitions(); + //3.把BeanDefinition对应的实例放入到IOC容器 + doRegisterBeanDefinition(beanDefinitions); + + //初始化阶段完成 + + //4.完成依赖注入 + doAutowrited(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 依赖注入(DI) + */ + private void doAutowrited() { + for (Map.Entry beanDefinitionEntry : this.beanDefinitionMap.entrySet()) { + String beanName = beanDefinitionEntry.getKey(); + getBean(beanName); + } + } + + + public Object getBean(String beanName) { + //1.读取bean信息 + MyBeanDefinition beanDefinition = this.beanDefinitionMap.get(beanName); + //2.反射实例化 + Object instance = instantiateBean(beanName, beanDefinition); + //3.把创建出来的真实实例包装为BeanWrapper对象 + MyBeanWrapper beanWrapper = new MyBeanWrapper(instance); + //4.把BeanWrapper对象放入真正的IOC容器里面 + this.factoryBeanInstanceCache.put(beanName, beanWrapper); + //5.执行依赖注入(DI) + populateBean(beanName, new MyBeanDefinition(), beanWrapper); + + return this.factoryBeanInstanceCache.get(beanName).getWrapperInstance(); + } + + private void populateBean(String beanName, MyBeanDefinition myBeanDefinition, MyBeanWrapper beanWrapper) { + + Object instance = beanWrapper.getWrapperInstance(); + Class clazz = beanWrapper.getWrapperClass(); + + //只有加了注解的才进行依赖注入 + if (!(clazz.isAnnotationPresent(MyController.class) || clazz.isAnnotationPresent(MyServices.class))) { + return; + } + //拿到实例的所有字段 + //Declared 所有的,特定的 字段,包括privave/protected/default + //正常来说,普通的OOP编程只能拿到public的属性 + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + if (!field.isAnnotationPresent(MyAutoWirted.class)) { + continue; + } + MyAutoWirted autoWirted = field.getAnnotation(MyAutoWirted.class); + //如果用户没有自定义beanName,默认就根据类型注入 + String autowiredBeanName = autoWirted.value().trim(); + if ("".equals(autowiredBeanName)) { + //获得接口的类型,拿这个key到ioc容器中取值 + autowiredBeanName = field.getType().getName(); + } + + //如果是public以外的修饰符,只要加了@Autowired注解,都要强制赋值 + //反射中叫暴力访问,强吻 + field.setAccessible(true); + + //反射调用的方式 + //给entry.getValue这个对象的field字段,赋值ioc.get(beanName) + + if (this.factoryBeanInstanceCache.get(autowiredBeanName) == null) { + continue; + } + + try { + Object beanInstance = this.factoryBeanInstanceCache.get(beanName).getWrapperInstance(); + field.set(instance, beanInstance); + } catch (IllegalAccessException e) { + e.printStackTrace(); + continue; + } + } + } + + + private Object instantiateBean(String beanName, MyBeanDefinition beanDefinition) { + + String className = beanDefinition.getBeanClassName(); + + Object instance = null; + try { + Class clazz = Class.forName(className); + instance = clazz.newInstance(); + + //TODO 未完 + /*//1、读取通知和目标类的关联关系 + GPAdvisedSupport config = instantionAopConfig(gpBeanDefinition); + config.setTargetClass(clazz); + config.setTarget(instance); + //2、生成一个代理类 + //不是所有的类都会生成代理类 + if(config.pointCutMatch()) { + instance = new GPJdkDynamicAopProxy(config).getProxy(); + } + this.factoryBeanObjectCache.put(beanName,instance); +*/ + + } catch (Exception e) { + e.printStackTrace(); + } + return instance; + } + + /** + * 存入IOC容器 + * + * @param beanDefinitions + */ + private void doRegisterBeanDefinition(List beanDefinitions) throws Exception { + for (MyBeanDefinition beanDefinition : beanDefinitions) { + if (this.beanDefinitionMap.containsKey(beanDefinition.getFactoryBeanName())) { + throw new Exception("The " + beanDefinition.getFactoryBeanName() + " is exists"); + } + this.beanDefinitionMap.put(beanDefinition.getFactoryBeanName(), beanDefinition); + } + } + + /** + * 获取所有自定义BeanNames + * @return + */ + public String[] getBeanDefinitionNames() { + return beanDefinitionMap.keySet().toArray(new String[beanDefinitionMap.size()]); + } + + public Properties getConfig(){ + return this.reader.getConfig(); + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyDispatcherServlet.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyDispatcherServlet.java new file mode 100644 index 0000000000000000000000000000000000000000..a2603ec7d352f5dfaa1cb7934ee395907c8a0cba --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyDispatcherServlet.java @@ -0,0 +1,177 @@ +package com.lecoboy.handwritespring.spring.framework.webmvc.servlet; + +import com.lecoboy.handwritespring.spring.framework.annotation.MyController; +import com.lecoboy.handwritespring.spring.framework.annotation.MyRequestMapping; +import com.lecoboy.handwritespring.spring.framework.context.MyApplicationContext; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 手写Spring IOC DI MVC简单流程 + */ +public class MyDispatcherServlet extends HttpServlet { + + //应用上下文 + private MyApplicationContext context = null; + + //保存url和Method的对应关系 + private List handlerMappings = new ArrayList(); + private Map handlerAdapters = new HashMap(); + + //模板引擎列表 + private List viewResolvers = new ArrayList(); + + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + //偷懒 + this.doPost(req,resp); + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + //6.根据url调用method + try{ + doDispatch(req, resp); + + }catch (Exception e){ + e.printStackTrace(); + resp.getWriter().write("500 Exception, Detail: " + Arrays.toString(e.getStackTrace())); + } + } + + private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception { + //1、根据url拿到对应的handler + MyHandlerMapping handler = getHandler(req); + if(null == handler){ + processDispatchResult(req,resp,new MyModelAndView("404")); + return; + } + + //2、根据HandlerMapping拿到HandlerAdapter + MyHandlerAdapter ha = getHandlerAdapter(handler); + + //3、根据HandlerApdater拿到ModelAndView + MyModelAndView mv = ha.handle(req,resp,handler); + + //4、ViewResolver 拿到View + //将View 渲染成浏览器能够接收的结果 HTML字符串 + processDispatchResult(req,resp,mv); + + } + + private void processDispatchResult(HttpServletRequest req, HttpServletResponse resp, MyModelAndView mv) throws Exception { + if(null == mv){return;} + if(this.viewResolvers.isEmpty()){return;} + + for (MyViewResolver viewResolver : this.viewResolvers) { + MyView view = viewResolver.resolveViewName(mv.getViewName()); + view.render(mv.getModel(),req,resp); + return; + } + } + + private MyHandlerAdapter getHandlerAdapter(MyHandlerMapping handler) { + if(this.handlerAdapters.isEmpty()){return null;} + MyHandlerAdapter ha = this.handlerAdapters.get(handler); + return ha; + } + + private MyHandlerMapping getHandler(HttpServletRequest req) { + if(this.handlerMappings.isEmpty()){return null;} + String url = req.getRequestURI(); + String contextPath = req.getContextPath(); + url = url.replaceAll(contextPath,"").replaceAll("/+","/"); + + for (MyHandlerMapping handlerMapping : this.handlerMappings) { + Matcher matcher = handlerMapping.getPattern().matcher(url); + //url是用正则去匹配Controller中的配置信息 + if(!matcher.matches()){continue;} + return handlerMapping; + } + return null; + } + + @Override + public void init(ServletConfig config) throws ServletException { + + context = new MyApplicationContext(config.getInitParameter("contextConfigLocation")); + + //初始化mvc9大组件 + //HandlerMappint + //HandlerAdapter + //ViewResolver + initStrategies(context); + System.out.println("My Spring framework is init."); + } + + private void initStrategies(MyApplicationContext context) { + //初始化Url和Method对应关系 + initHandlerMappings(context); + //初始化参数适配器 + initHandlerAdapter(context); + //初始化视图转换器 + initViewResolver(context); + } + + private void initViewResolver(MyApplicationContext context) { + String templateRoot = context.getConfig().getProperty("templateRoot"); + String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile(); + File templateRootDir = new File(templateRootPath); + for (File file : templateRootDir.listFiles()) { + //templateRoot + //TODO + this.viewResolvers.add(new MyViewResolver(file.getPath())); + } + } + + private void initHandlerAdapter(MyApplicationContext context) { + for (MyHandlerMapping handlerMapping : handlerMappings) { + this.handlerAdapters.put(handlerMapping,new MyHandlerAdapter()); + } + } + + private void initHandlerMappings(MyApplicationContext context) { + //获取所有BeanNames + String[] beanNames = context.getBeanDefinitionNames(); + for (String beanName : beanNames) { + Object instance = context.getBean(beanName); + Class clazz = instance.getClass(); + //初始化Controller注解 + if (!clazz.isAnnotationPresent(MyController.class)) { + continue; + } + //保存注解类上面的@MyRequestMapping("/demo") + String baseUrl = ""; + if (clazz.isAnnotationPresent(MyRequestMapping.class)) { + MyRequestMapping requestMapping = clazz.getAnnotation(MyRequestMapping.class); + baseUrl = requestMapping.value(); + } + //默认获取所有public方法 + for (Method method : clazz.getMethods()) { + if (!method.isAnnotationPresent(MyRequestMapping.class)) { + continue; + } + MyRequestMapping requestMapping = method.getAnnotation(MyRequestMapping.class); + //防止有多个//或单/,进行正则替换 + //demoquery + // //demo//query + String regex = ("/" + baseUrl + "/" + requestMapping.value().replaceAll("\\*",".*")).replaceAll("/+","/"); + Pattern pattern = Pattern.compile(regex); + this.handlerMappings.add(new MyHandlerMapping(instance, method, pattern)); + System.out.println("Mapperd " + regex + "," + method); + } + + } + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyHandlerAdapter.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyHandlerAdapter.java new file mode 100644 index 0000000000000000000000000000000000000000..71a5adbb1fea6624a7043004efdb8201997ebe28 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyHandlerAdapter.java @@ -0,0 +1,113 @@ +package com.lecoboy.handwritespring.spring.framework.webmvc.servlet; + + +import com.lecoboy.handwritespring.spring.framework.annotation.MyRequestParam; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.lang.annotation.Annotation; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * 动态适配参数 + * @author leon + */ +public class MyHandlerAdapter { + /** + * 形参和实参赋值 + * @param request + * @param response + * @param handler + * @return + * @throws Exception + */ + public MyModelAndView handle(HttpServletRequest request, HttpServletResponse response, MyHandlerMapping handler) throws Exception{ + + //拼接形参列表 + //保存了Controller的方法上配置的参数名字以及和参数位置的对应关系 + Map paramIndexMapping = new HashMap(); + + //提取方法中加了注解的参数 + Annotation[] [] pa = handler.getMethod().getParameterAnnotations(); + for (int i = 0; i < pa.length ; i ++) { + for(Annotation a : pa[i]){ + if(a instanceof MyRequestParam){ + String paramName = ((MyRequestParam) a).value(); + if(!"".equals(paramName.trim())){ + paramIndexMapping.put(paramName, i); + } + } + } + } + + //提取方法中的request和response参数 + Class [] paramsTypes = handler.getMethod().getParameterTypes(); + for (int i = 0; i < paramsTypes.length ; i ++) { + Class type = paramsTypes[i]; + if(type == HttpServletRequest.class || + type == HttpServletResponse.class){ + paramIndexMapping.put(type.getName(),i); + } + } + + //拼接实参列表 + + Map paramsMap = request.getParameterMap(); + + Object [] parameValues = new Object[paramsTypes.length]; + + for (Map.Entry param : paramsMap.entrySet()) { + String value = Arrays.toString(paramsMap.get(param.getKey())) + .replaceAll("\\[|\\]","") + .replaceAll("\\s",","); + if(!paramIndexMapping.containsKey(param.getKey())){continue;} + + int index = paramIndexMapping.get(param.getKey()); + parameValues[index] = caseStringValue(value,paramsTypes[index]); + } + + if(paramIndexMapping.containsKey(HttpServletRequest.class.getName())){ + int index = paramIndexMapping.get(HttpServletRequest.class.getName()); + parameValues[index] = request; + } + + if(paramIndexMapping.containsKey(HttpServletResponse.class.getName())){ + int index = paramIndexMapping.get(HttpServletResponse.class.getName()); + parameValues[index] = response; + } + + Object result = handler.getMethod().invoke(handler.getController(),parameValues); + if(result == null || result instanceof Void){return null;} + + boolean isModelAndView = handler.getMethod().getReturnType() == MyModelAndView.class; + if(isModelAndView){ + return (MyModelAndView)result; + } + return null; + } + + /** + * 解析参数类型 + * @param value + * @param paramType + * @return + */ + private Object caseStringValue(String value,Class paramType){ + if(String.class == paramType){ + return value; + } + //TODO 可继续扩展 + if(Integer.class == paramType){ + return Integer.valueOf(value); + }else if(Double.class == paramType){ + return Double.valueOf(value); + } else{ + if(value != null){ + return value; + } + return null; + } + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyHandlerMapping.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyHandlerMapping.java new file mode 100644 index 0000000000000000000000000000000000000000..c196761278ed56c9c5204d0c3d85a235fb382377 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyHandlerMapping.java @@ -0,0 +1,44 @@ +package com.lecoboy.handwritespring.spring.framework.webmvc.servlet; + +import java.lang.reflect.Method; +import java.util.regex.Pattern; + +/** + * 保存url映射关系 + * @author lecon + */ +public class MyHandlerMapping { + protected Object controller; //保存方法对应的实例 + protected Method method; //保存方法的映射 + protected Pattern pattern; //${ } 占位符解析 + + public MyHandlerMapping(Object controller, Method method, Pattern pattern) { + this.controller = controller; + this.method = method; + this.pattern = pattern; + } + + public Object getController() { + return controller; + } + + public void setController(Object controller) { + this.controller = controller; + } + + public Method getMethod() { + return method; + } + + public void setMethod(Method method) { + this.method = method; + } + + public Pattern getPattern() { + return pattern; + } + + public void setPattern(Pattern pattern) { + this.pattern = pattern; + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyModelAndView.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyModelAndView.java new file mode 100644 index 0000000000000000000000000000000000000000..1a9e2a8f648bb919be26bef0f23d3ac7f9f7d850 --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyModelAndView.java @@ -0,0 +1,29 @@ +package com.lecoboy.handwritespring.spring.framework.webmvc.servlet; + +import java.util.Map; + +/** + * 页面渲染视图 + * @author leon + */ +public class MyModelAndView { + private String viewName; + private Map model; + + public MyModelAndView(String viewName, Map model) { + this.viewName = viewName; + this.model = model; + } + + public MyModelAndView(String viewName) { + this.viewName = viewName; + } + + public String getViewName() { + return viewName; + } + + public Map getModel() { + return model; + } +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyView.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyView.java new file mode 100644 index 0000000000000000000000000000000000000000..c3cbc68c4cf50fa2c4dbfbc66b950a238740f06a --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyView.java @@ -0,0 +1,60 @@ +package com.lecoboy.handwritespring.spring.framework.webmvc.servlet; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.RandomAccessFile; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class MyView { + + private File viewFile; + + public MyView(File templateFile) { + this.viewFile = templateFile; + } + + public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception{ + + //第一步,就是把模板文件的内容读出来 + StringBuffer sb = new StringBuffer(); + RandomAccessFile ra = new RandomAccessFile(this.viewFile,"r"); + + //解析,把模板里面写的模板语言替换掉 + String line = null; + while (null != (line = ra.readLine())){ + line = new String(line.getBytes("ISO-8859-1"),"utf-8"); + Pattern pattern = Pattern.compile("¥\\{[^\\}]+\\}",Pattern.CASE_INSENSITIVE); + Matcher mather = pattern.matcher(line); + while (mather.find()){ + String paramName = mather.group(); + paramName = paramName.replaceAll("¥\\{|\\}",""); + Object paramVlue = model.get(paramName); + if(null == paramVlue){continue;} + line = mather.replaceFirst(makeStringForRegExp(paramVlue.toString())); + mather = pattern.matcher(line); + } + sb.append(line); + } + + response.setCharacterEncoding("utf-8"); + response.setContentType("text/html;charset=utf-8"); + response.getWriter().write(sb.toString()); + } + + + //处理特殊字符 + public static String makeStringForRegExp(String str) { + return str.replace("\\", "\\\\").replace("*", "\\*") + .replace("+", "\\+").replace("|", "\\|") + .replace("{", "\\{").replace("}", "\\}") + .replace("(", "\\(").replace(")", "\\)") + .replace("^", "\\^").replace("$", "\\$") + .replace("[", "\\[").replace("]", "\\]") + .replace("?", "\\?").replace(",", "\\,") + .replace(".", "\\.").replace("&", "\\&"); + } + +} diff --git a/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyViewResolver.java b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyViewResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..92676016b75315a112a8757614751efef881d43b --- /dev/null +++ b/handwritespring/src/main/java/com/lecoboy/handwritespring/spring/framework/webmvc/servlet/MyViewResolver.java @@ -0,0 +1,28 @@ +package com.lecoboy.handwritespring.spring.framework.webmvc.servlet; + +import java.io.File; + +/** + * 视图转换器,模板引擎 + * @author leon + */ +public class MyViewResolver { + + //.jsp .vm .ftl 默认给.html + private final String DEAULT_TEMPLATE_SUFFX = ".html"; + + private File templateRootDir; + + public MyViewResolver(String teamplateRoot){ + String templateRootPath = this.getClass().getClassLoader().getResource(teamplateRoot).getFile(); + templateRootDir = new File(templateRootPath); + } + + public MyView resolveViewName(String viewName){ + if(null == viewName || "".equals(viewName.trim())){return null;} + + viewName = viewName.endsWith(DEAULT_TEMPLATE_SUFFX) ? viewName : (viewName + DEAULT_TEMPLATE_SUFFX); + File templateFile = new File((templateRootDir.getPath() + "/" + viewName).replaceAll("/+","/")); + return new MyView(templateFile); + } +} diff --git a/handwritespring/src/main/resources/application.properties b/handwritespring/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..c3f0c1c2a6abe283703ef9c15b0ee5d14c8baa5d --- /dev/null +++ b/handwritespring/src/main/resources/application.properties @@ -0,0 +1,39 @@ +#扫描包 +scanPackage=com.lecoboy.handwritespring +#模板路径 +templateRoot=layouts + +#\u591A\u5207\u9762\u914D\u7F6E\u53EF\u4EE5\u5728key\u524D\u9762\u52A0\u524D\u7F00 +#\u4F8B\u5982 aspect.logAspect. + +#\u5207\u9762\u8868\u8FBE\u5F0F,expression# +pointCut=public .* com.gupaoedu.vip.demo.service..*Service..*(.*) +#\u5207\u9762\u7C7B# +aspectClass=com.gupaoedu.vip.demo.aspect.LogAspect +#\u5207\u9762\u524D\u7F6E\u901A\u77E5# +aspectBefore=before +#\u5207\u9762\u540E\u7F6E\u901A\u77E5# +aspectAfter=after +#\u5207\u9762\u5F02\u5E38\u901A\u77E5# +aspectAfterThrow=afterThrowing +#\u5207\u9762\u5F02\u5E38\u7C7B\u578B# +aspectAfterThrowingName=java.lang.Exception + + +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# diff --git a/handwritespring/src/main/resources/layouts/404.html b/handwritespring/src/main/resources/layouts/404.html new file mode 100755 index 0000000000000000000000000000000000000000..b996c7e3bc79cb7ce419c3c64bc94d31f6bc089d --- /dev/null +++ b/handwritespring/src/main/resources/layouts/404.html @@ -0,0 +1,10 @@ + + + + + 页面去火星了 + + + 404 Not Found
Copyright@GupaoEDU + + \ No newline at end of file diff --git a/handwritespring/src/main/resources/layouts/500.html b/handwritespring/src/main/resources/layouts/500.html new file mode 100755 index 0000000000000000000000000000000000000000..c7b75a72135d548329c976342936169d129b424d --- /dev/null +++ b/handwritespring/src/main/resources/layouts/500.html @@ -0,0 +1,13 @@ + + + + + 服务器好像累了 + + +500 服务器好像有点累了,需要休息一下
+Message:¥{detail}
+StackTrace:¥{stackTrace}
+Copyright@GupaoEDU + + \ No newline at end of file diff --git a/handwritespring/src/main/resources/layouts/first.html b/handwritespring/src/main/resources/layouts/first.html new file mode 100755 index 0000000000000000000000000000000000000000..1452fdcb3e7c1bfcd0306a93dd819277f31fe679 --- /dev/null +++ b/handwritespring/src/main/resources/layouts/first.html @@ -0,0 +1,13 @@ + + + + + 咕泡学院SpringMVC模板引擎演示 + +
+

大家好,我是¥{teacher}老师
欢迎大家一起来探索Spring的世界

+

Hello,My name is ¥{teacher}

+
¥{data}
+ Token值:¥{token} +
+ \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 416785b9a743e27337d89c37dccf4c316312dfc1..f0f694b9f9a0b2abb54400afb594db8bd491f460 100644 --- a/settings.gradle +++ b/settings.gradle @@ -4,4 +4,6 @@ rootProject.name = 'daydayup' include 'daydayup-design-patterns' include 'daydayup-algorithm' include 'daydayup-rocket-mq-study' -include 'daydayup-high-concurrency' \ No newline at end of file +include 'daydayup-high-concurrency' +include 'handwritespring' +include 'daydayup-shardingdb' \ No newline at end of file