diff --git a/.gitignore b/.gitignore index 966499f4..ba5fe28e 100644 --- a/.gitignore +++ b/.gitignore @@ -22,4 +22,7 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* *.iml -*.idea/ \ No newline at end of file +*.idea/ +*target + +.DS_Store \ No newline at end of file diff --git a/02nio/nio01/src/main/java/java0/nio01/HttpServer02.java b/02nio/nio01/src/main/java/java0/nio01/HttpServer02.java index 9b51cf29..5a925776 100644 --- a/02nio/nio01/src/main/java/java0/nio01/HttpServer02.java +++ b/02nio/nio01/src/main/java/java0/nio01/HttpServer02.java @@ -7,7 +7,7 @@ public class HttpServer02 { public static void main(String[] args) throws IOException{ - ServerSocket serverSocket = new ServerSocket(8802); + ServerSocket serverSocket = new ServerSocket(8089); while (true) { try { final Socket socket = serverSocket.accept(); diff --git a/02nio/nio01/src/main/java/java0/nio01/HttpServer03.java b/02nio/nio01/src/main/java/java0/nio01/HttpServer03.java index fad136a8..cde4c1d3 100644 --- a/02nio/nio01/src/main/java/java0/nio01/HttpServer03.java +++ b/02nio/nio01/src/main/java/java0/nio01/HttpServer03.java @@ -10,7 +10,7 @@ public class HttpServer03 { public static void main(String[] args) throws IOException{ ExecutorService executorService = Executors.newFixedThreadPool(40); - final ServerSocket serverSocket = new ServerSocket(8803); + final ServerSocket serverSocket = new ServerSocket(8089); while (true) { try { final Socket socket = serverSocket.accept(); diff --git a/02nio/nio02/pom.xml b/02nio/nio02/pom.xml index 6cbbeffd..e751f5fc 100644 --- a/02nio/nio02/pom.xml +++ b/02nio/nio02/pom.xml @@ -52,7 +52,12 @@ httpasyncclient 4.1.4 - + + + com.squareup.okhttp3 + okhttp + 3.6.0 + + 4.3.29.RELEASE + UTF-8 + UTF-8 + + + + org.projectlombok + lombok + 1.18.12 + + + org.springframework + spring-context + ${spring-version} + + + org.springframework + spring-core + ${spring-version} + + + org.springframework.boot + spring-boot-autoconfigure + 2.3.5.RELEASE + compile + + + \ No newline at end of file diff --git a/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/StudentAutoConfiguration.java b/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/StudentAutoConfiguration.java new file mode 100644 index 00000000..23c6c200 --- /dev/null +++ b/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/StudentAutoConfiguration.java @@ -0,0 +1,29 @@ +package example.springboot.starter; + +import example.springboot.starter.service.Student; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConditionalOnClass(Student.class) +@EnableConfigurationProperties(StudentProperties.class) +@ConditionalOnProperty(prefix = "example.student", value = "enabled", matchIfMissing = true) +public class StudentAutoConfiguration { + + @Autowired + private StudentProperties studentProperties; + + @Bean + @ConditionalOnMissingBean(Student.class) + public Student student() { + Student student = new Student(); + student.setId(studentProperties.getId()); + student.setName(studentProperties.getName()); + return student; + } +} diff --git a/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/StudentProperties.java b/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/StudentProperties.java new file mode 100644 index 00000000..d34cf22e --- /dev/null +++ b/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/StudentProperties.java @@ -0,0 +1,25 @@ +package example.springboot.starter; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "example.student") +public class StudentProperties { + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/service/Student.java b/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/service/Student.java new file mode 100644 index 00000000..7a93fa94 --- /dev/null +++ b/04spring/example-spring-boot-starter/src/main/java/example/springboot/starter/service/Student.java @@ -0,0 +1,29 @@ +package example.springboot.starter.service; + + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.io.Serializable; + + +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString + +public class Student implements Serializable { + + private int id; + private String name; + + public void init(){ + System.out.println("hello..........."); + } + + public Student create(){ + return new Student(101,"KK101"); + } +} diff --git a/04spring/example-spring-boot-starter/src/main/resources/META-INF/spring.factories b/04spring/example-spring-boot-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..0dce1c63 --- /dev/null +++ b/04spring/example-spring-boot-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + example.springboot.starter.StudentAutoConfiguration \ No newline at end of file diff --git a/04spring/example-spring-boot-starter/target/classes/META-INF/spring.factories b/04spring/example-spring-boot-starter/target/classes/META-INF/spring.factories new file mode 100644 index 00000000..0dce1c63 --- /dev/null +++ b/04spring/example-spring-boot-starter/target/classes/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + example.springboot.starter.StudentAutoConfiguration \ No newline at end of file diff --git a/04spring/example-spring-boot-starter/target/maven-archiver/pom.properties b/04spring/example-spring-boot-starter/target/maven-archiver/pom.properties new file mode 100644 index 00000000..1d3dde19 --- /dev/null +++ b/04spring/example-spring-boot-starter/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Wed Nov 18 16:02:42 GMT+08:00 2020 +version=1.0-SNAPSHOT +groupId=example.springboot +artifactId=example-spring-boot-starter diff --git a/04spring/example-spring-boot-starter/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/04spring/example-spring-boot-starter/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 00000000..aed12f76 --- /dev/null +++ b/04spring/example-spring-boot-starter/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -0,0 +1,3 @@ +example\springboot\starter\service\Student.class +example\springboot\starter\StudentProperties.class +example\springboot\starter\StudentAutoConfiguration.class diff --git a/04spring/example-spring-boot-starter/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/04spring/example-spring-boot-starter/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 00000000..f89d2be7 --- /dev/null +++ b/04spring/example-spring-boot-starter/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -0,0 +1,3 @@ +D:\wangyibing\JavaCourseCodes\04spring\example-spring-boot-starter\src\main\java\example\springboot\starter\service\Student.java +D:\wangyibing\JavaCourseCodes\04spring\example-spring-boot-starter\src\main\java\example\springboot\starter\StudentAutoConfiguration.java +D:\wangyibing\JavaCourseCodes\04spring\example-spring-boot-starter\src\main\java\example\springboot\starter\StudentProperties.java diff --git a/04spring/example-spring-boot-starter/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst b/04spring/example-spring-boot-starter/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst new file mode 100644 index 00000000..e69de29b diff --git a/04spring/jdbc/pom.xml b/04spring/jdbc/pom.xml new file mode 100644 index 00000000..2f8ec41c --- /dev/null +++ b/04spring/jdbc/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + jdbc + jdbc-demo + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 7 + 7 + + + + + + + mysql + mysql-connector-java + 8.0.16 + + + junit + junit + 4.12 + + + org.projectlombok + lombok + 1.18.12 + + + com.zaxxer + HikariCP + 3.4.5 + + + + + + \ No newline at end of file diff --git a/04spring/jdbc/src/main/java/com/github/yibing/jdbc/DBUtils.java b/04spring/jdbc/src/main/java/com/github/yibing/jdbc/DBUtils.java new file mode 100644 index 00000000..cd8c23ea --- /dev/null +++ b/04spring/jdbc/src/main/java/com/github/yibing/jdbc/DBUtils.java @@ -0,0 +1,67 @@ +package com.github.yibing.jdbc; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; + +import java.sql.*; + +public class DBUtils { + private static final String driver = "com.mysql.jdbc.Driver"; + private static final String url = "jdbc:mysql://localhost:3306/student?&serverTimezone=Asia/Shanghai"; + private static final String username = "root"; + private static final String password = ""; + private static Connection connection = null; + + public static Connection getConnection() { + try { + Class.forName("com.mysql.jdbc.Driver"); + connection = DriverManager.getConnection(url, username, password); + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + } + return connection; + } + + public static Connection getHikariConnection() { + HikariConfig config = new HikariConfig(); + config.setJdbcUrl(url); + config.setUsername(username); + config.setPassword(password); + HikariDataSource dataSource = new HikariDataSource(config); + try { + connection = dataSource.getConnection(); + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + return connection; + } + + public static void closeConnection(Connection connection, Statement statement) { + try { + if (connection != null) { + connection.close(); + } + if (statement != null) { + statement.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void closeConnection(Connection connection, Statement statement, ResultSet resultSet) { + try { + if (connection != null) { + connection.close(); + } + if (statement != null) { + statement.close(); + } + if (resultSet != null) { + resultSet.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/04spring/jdbc/src/main/java/com/github/yibing/jdbc/JdbcDemo.java b/04spring/jdbc/src/main/java/com/github/yibing/jdbc/JdbcDemo.java new file mode 100644 index 00000000..c8b0aefc --- /dev/null +++ b/04spring/jdbc/src/main/java/com/github/yibing/jdbc/JdbcDemo.java @@ -0,0 +1,127 @@ +package com.github.yibing.jdbc; + +import com.github.yibing.jdbc.domain.Student; +import org.junit.Test; + +import java.sql.*; +import java.util.ArrayList; + +public class JdbcDemo { + private static Connection connection = null; + + public static void main(String[] args) { + + } + + // 查询 + @Test + public void queryStudent() { + String sql = "select * from student"; + connection = DBUtils.getConnection(); + ResultSet resultSet = null; + Statement statement = null; + try { + statement = connection.createStatement(); + resultSet = statement.executeQuery(sql); + while (resultSet.next()) { + System.out.println("id = " + resultSet.getString("id")); + System.out.println("name = " + resultSet.getString("name")); + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } finally { + DBUtils.closeConnection(connection, statement, resultSet); + } + } + // 插入 + @Test + public void insertOne() { + Student student = new Student(3, "李华"); + Connection connection = DBUtils.getConnection(); + PreparedStatement psmt = null; + try { + psmt = connection.prepareStatement("insert into student values(?,?)"); + psmt.setInt(1, student.getId()); + psmt.setString(2, student.getName()); + int i = psmt.executeUpdate(); + if (i > 0) { + System.out.println("成功----" + i); + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } finally { + DBUtils.closeConnection(connection, psmt); + } + + } + // 删除一个 + @Test + public void deleteOne() { + Connection connection = DBUtils.getConnection(); + PreparedStatement psmt = null; + try { + psmt = connection.prepareStatement("delete from student where id = ?"); + psmt.setInt(1, 3); + int i = psmt.executeUpdate(); + if (i > 0) { + System.out.println("删除成功--" + i + "条"); + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } finally { + DBUtils.closeConnection(connection, psmt); + } + } + // 修改 + @Test + public void updateOne() { + Student student = new Student(1, "小明"); + Connection connection = DBUtils.getConnection(); + PreparedStatement psmt = null; + + try { + psmt = connection.prepareStatement("update student set name = ? where id = ?"); + int i = psmt.executeUpdate(); + if (i > 0) { + System.out.println("已修改" + i + "条"); + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } finally { + DBUtils.closeConnection(connection, psmt); + } + + } + // 批量插入 + @Test + public void batchInsert() { + ArrayList list = new ArrayList(); + for (int i = 0; i < 100000; i++) { + list.add(new Student("student" + i)); + } + // 使用 JDBC +// Connection connection = DBUtils.getConnection(); + // 使用 Hikari连接池 + Connection connection = DBUtils.getHikariConnection(); + String sql = "insert into student (name) values (?)"; + PreparedStatement psmt = null; + try { + psmt = connection.prepareStatement(sql); + connection.setAutoCommit(false); + for (int i = 0; i < list.size(); i++) { + psmt.setString(1, list.get(i).getName()); + psmt.executeUpdate(); + } + connection.commit(); + } catch (SQLException throwables) { + throwables.printStackTrace(); + try { + connection.rollback(); + } catch (SQLException e) { + e.printStackTrace(); + } + } finally { + DBUtils.closeConnection(connection, psmt); + } + } +} diff --git a/04spring/jdbc/src/main/java/com/github/yibing/jdbc/domain/Student.java b/04spring/jdbc/src/main/java/com/github/yibing/jdbc/domain/Student.java new file mode 100644 index 00000000..55de5233 --- /dev/null +++ b/04spring/jdbc/src/main/java/com/github/yibing/jdbc/domain/Student.java @@ -0,0 +1,19 @@ +package com.github.yibing.jdbc.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@ToString +public class Student { + private int id; + private String name; + + public Student(String name) { + this.name = name; + } +} diff --git a/04spring/spring01/pom.xml b/04spring/spring01/pom.xml new file mode 100644 index 00000000..dcb8099d --- /dev/null +++ b/04spring/spring01/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.0 + + + org.github.yibing + springioc + 1.0-SNAPSHOT + + + 4.3.29.RELEASE + + + + + org.springframework + spring-context + + + org.springframework.boot + spring-boot-starter + + + junit + junit + 4.12 + + + org.projectlombok + lombok + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/Spring01Application.java b/04spring/spring01/src/main/java/org/github/yibing/spring/Spring01Application.java new file mode 100644 index 00000000..5702b527 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/Spring01Application.java @@ -0,0 +1,11 @@ +package org.github.yibing.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Spring01Application { + public static void main(String[] args) { + SpringApplication.run(Spring01Application.class, args); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/Animal.java b/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/Animal.java new file mode 100644 index 00000000..e2bdc78d --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/Animal.java @@ -0,0 +1,5 @@ +package org.github.yibing.spring.aop.jdkproxy; + +public interface Animal { + void breathe(); +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/Bird.java b/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/Bird.java new file mode 100644 index 00000000..528ad26d --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/Bird.java @@ -0,0 +1,8 @@ +package org.github.yibing.spring.aop.jdkproxy; + +public class Bird implements Animal { + @Override + public void breathe() { + System.out.println("animal can breathe.."); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/BirdProxy.java b/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/BirdProxy.java new file mode 100644 index 00000000..546d2b7e --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/BirdProxy.java @@ -0,0 +1,21 @@ +package org.github.yibing.spring.aop.jdkproxy; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + +public class BirdProxy implements InvocationHandler { + + private Animal bird; + + public BirdProxy(Animal bird) { + this.bird = bird; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + System.out.println("before invoke ........"); + Object obj = method.invoke(bird, args); + System.out.println("after invoke ...."); + return obj; + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/JdkProxyDemo.java b/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/JdkProxyDemo.java new file mode 100644 index 00000000..452a0a47 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/aop/jdkproxy/JdkProxyDemo.java @@ -0,0 +1,13 @@ +package org.github.yibing.spring.aop.jdkproxy; + +import java.lang.reflect.Proxy; + +public class JdkProxyDemo { + public static void main(String[] args) { + Animal bird = new Bird(); + BirdProxy birdProxy = new BirdProxy(bird); + Animal instance = (Animal) Proxy.newProxyInstance(bird.getClass().getClassLoader(), bird.getClass().getInterfaces(), birdProxy); + System.out.println("代理的类型:" + bird.getClass().getName()); + instance.breathe(); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/annotation/Super.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/annotation/Super.java new file mode 100644 index 00000000..4758ac56 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/annotation/Super.java @@ -0,0 +1,11 @@ +package org.github.yibing.spring.ioc.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Super { +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/AppConfig.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/AppConfig.java new file mode 100644 index 00000000..bd0a608d --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/AppConfig.java @@ -0,0 +1,15 @@ +package org.github.yibing.spring.ioc.autowire; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("org.github.yibing.spring.ioc.autowire") +public class AppConfig { + +// @Bean +// public Student student() { +// return new Student(); +// } + +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/InstantiateDemo.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/InstantiateDemo.java new file mode 100644 index 00000000..bce77baa --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/InstantiateDemo.java @@ -0,0 +1,26 @@ +package org.github.yibing.spring.ioc.autowire; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class InstantiateDemo { + + public static void main(String[] args) { +// javaconfig(); +// xmlconfig(); + } + + + private static void xmlconfig() { + BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:instantiate-type.xml"); + Teacher teacher = (Teacher) beanFactory.getBean("teacher"); + System.out.println(teacher); + } + + private static void javaconfig() { + BeanFactory beanFactory = new AnnotationConfigApplicationContext(AppConfig.class); + Student student = (Student) beanFactory.getBean("student"); + System.out.println(student); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/Student.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/Student.java new file mode 100644 index 00000000..638f1d16 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/Student.java @@ -0,0 +1,39 @@ +package org.github.yibing.spring.ioc.autowire; + +import org.springframework.stereotype.Component; + +@Component("student") + +public class Student { + private String id; + private String name; + + public void init() { + System.out.println("hello..........."+this.name); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Student{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + '}'; + } +} + diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/Teacher.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/Teacher.java new file mode 100644 index 00000000..f6425a61 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/autowire/Teacher.java @@ -0,0 +1,41 @@ +package org.github.yibing.spring.ioc.autowire; + +public class Teacher { + private String subject; + private String id; + // 依赖Student类 + private Student student; + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Student getStudent() { + return student; + } + + public void setStudent(Student student) { + this.student = student; + } + + @Override + public String toString() { + return "Teacher{" + + "subject='" + subject + '\'' + + ", id='" + id + '\'' + + ", student=" + student + + '}'; + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/A.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/A.java new file mode 100644 index 00000000..7000c332 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/A.java @@ -0,0 +1,9 @@ +package org.github.yibing.spring.ioc.cycleDI; + +import org.springframework.stereotype.Service; + +@Service +public class A { + public A(B b) { + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/B.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/B.java new file mode 100644 index 00000000..440e6654 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/B.java @@ -0,0 +1,9 @@ +package org.github.yibing.spring.ioc.cycleDI; + +import org.springframework.stereotype.Service; + +@Service +public class B { + public B(C c) { + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/C.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/C.java new file mode 100644 index 00000000..1668c512 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/cycleDI/C.java @@ -0,0 +1,9 @@ +package org.github.yibing.spring.ioc.cycleDI; + +import org.springframework.stereotype.Service; + +@Service +public class C { + public C(A a) { + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/domain/SuperUser.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/domain/SuperUser.java new file mode 100644 index 00000000..f184958c --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/domain/SuperUser.java @@ -0,0 +1,21 @@ +package org.github.yibing.spring.ioc.domain; + +import org.github.yibing.spring.ioc.annotation.Super; + +@Super +public class SuperUser extends User { + private String address; + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String toString() { + return "SuperUser{} " + super.toString(); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/domain/User.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/domain/User.java new file mode 100644 index 00000000..1ce7ddb9 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/domain/User.java @@ -0,0 +1,30 @@ +package org.github.yibing.spring.ioc.domain; + +public class User { + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "User{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + '}'; + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/lookup/DependencyLookupDemo.java b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/lookup/DependencyLookupDemo.java new file mode 100644 index 00000000..57b5b5b9 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/ioc/lookup/DependencyLookupDemo.java @@ -0,0 +1,53 @@ +package org.github.yibing.spring.ioc.lookup; + +import org.github.yibing.spring.ioc.annotation.Super; +import org.github.yibing.spring.ioc.domain.User; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.util.Map; + +public class DependencyLookupDemo { + public static void main(String[] args) { + BeanFactory context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); + lookupInRealTime(context); +// lookupInLazy(context); +// lookupByType(context); +// lookupCollectionByType(context); +// lookupByAnnotation(context); + } + + private static void lookupByAnnotation(BeanFactory context) { + if(context instanceof ListableBeanFactory){ + ListableBeanFactory listableBeanFactory = (ListableBeanFactory) context; + Map users = listableBeanFactory.getBeansWithAnnotation(Super.class); + System.out.println("按注解查找集合:"+users); + } + } + + private static void lookupCollectionByType(BeanFactory context) { + if(context instanceof ListableBeanFactory){ + ListableBeanFactory listableBeanFactory = (ListableBeanFactory) context; + Map users = listableBeanFactory.getBeansOfType(User.class); + System.out.println("按类型查找集合:"+users); + } + } + + private static void lookupByType(BeanFactory context) { + User user = context.getBean(User.class); + System.out.println("按类型查找:"+user); + } + + private static void lookupInLazy(BeanFactory context) { + ObjectFactory objectFactory = (ObjectFactory) context.getBean("objectFactory"); + User user = objectFactory.getObject(); + System.out.println("延迟查找:"+user); + } + + private static void lookupInRealTime(BeanFactory context) { + User user = (User) context.getBean("user"); + System.out.println("实时查找:"+user); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/Context.java b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/Context.java new file mode 100644 index 00000000..5401bdbd --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/Context.java @@ -0,0 +1,13 @@ +package org.github.yibing.spring.strategy; + +public class Context { + private Strategy strategy; + + public Context(Strategy strategy) { + this.strategy = strategy; + } + + public int executeStrategy(int num1, int num2) { + return strategy.doOperation(num1, num2); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationAdd.java b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationAdd.java new file mode 100644 index 00000000..3ce80f93 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationAdd.java @@ -0,0 +1,8 @@ +package org.github.yibing.spring.strategy; + +public class OperationAdd implements Strategy { + @Override + public int doOperation(int num1, int num2) { + return num1 + num2; + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationMultiply.java b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationMultiply.java new file mode 100644 index 00000000..d20e7de0 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationMultiply.java @@ -0,0 +1,8 @@ +package org.github.yibing.spring.strategy; + +public class OperationMultiply implements Strategy { + @Override + public int doOperation(int num1, int num2) { + return num1 * num2; + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationSubtract.java b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationSubtract.java new file mode 100644 index 00000000..153870c6 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/OperationSubtract.java @@ -0,0 +1,8 @@ +package org.github.yibing.spring.strategy; + +public class OperationSubtract implements Strategy { + @Override + public int doOperation(int num1, int num2) { + return num1 + num2; + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/Strategy.java b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/Strategy.java new file mode 100644 index 00000000..f23e0eb5 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/Strategy.java @@ -0,0 +1,5 @@ +package org.github.yibing.spring.strategy; + +public interface Strategy { + public int doOperation(int num1, int num2); +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/StrategyDemo.java b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/StrategyDemo.java new file mode 100644 index 00000000..8c2e7cc7 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/strategy/StrategyDemo.java @@ -0,0 +1,10 @@ +package org.github.yibing.spring.strategy; + +public class StrategyDemo { + public static void main(String[] args) { + Context context = new Context(new OperationAdd()); + System.out.println("10+6=" + context.executeStrategy(10, 6)); + context = new Context(new OperationSubtract()); + System.out.println("10-6=" + context.executeStrategy(10, 6)); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/stream/Employee.java b/04spring/spring01/src/main/java/org/github/yibing/spring/stream/Employee.java new file mode 100644 index 00000000..6f7ec1d2 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/stream/Employee.java @@ -0,0 +1,18 @@ +package org.github.yibing.spring.stream; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString +public class Employee { + private int id; + private String name; + private int age; + private Double salary; + +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/stream/StreamDemo.java b/04spring/spring01/src/main/java/org/github/yibing/spring/stream/StreamDemo.java new file mode 100644 index 00000000..412a7d47 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/stream/StreamDemo.java @@ -0,0 +1,125 @@ +package org.github.yibing.spring.stream; + +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class StreamDemo { + List emps = Arrays.asList(new Employee(101, "张三", 28, 9999d), + new Employee(101, "李四", 49, 666d), + new Employee(102, "王五", 38, 333d), + new Employee(103, "赵六", 12, 7777d), + new Employee(104, "田七", 6, 222d) + ); + + public static void main(String[] args) { + /** + * stream 的创建方式 + */ + + // 集合创建 + ArrayList list = new ArrayList<>(); + Stream stream = list.stream(); + // 数组创建 + Integer[] integers = new Integer[10]; + Stream stream1 = Arrays.stream(integers); + // Stream静态方法传概念 + Stream stream2 = Stream.of(1, 2, 3, 4, 5, 6); + // 创建无线流 + Stream stream3 = Stream.iterate(0, (x) -> x + 1); + + + } + + // 中间操作-过滤 + @Test + public void test1() { + emps.stream() + .filter((e) -> e.getAge() > 20) + .limit(2) // limit(long n) :截取前面 n 条 , skip(long n):跳过前面 n 条 + .forEach(System.out::println); + } + + // 中间操作-映射 + @Test + public void test2() { + List strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee"); + Stream stream = strList.stream().map(String::toUpperCase); + stream.forEach(System.out::println); + +// Stream> stream1 = strList.stream().map(StreamDemo::filterCharacter); +// stream1.forEach((sm) -> { +// sm.forEach(System.out::print); +// }); + Stream stream2 = strList.stream().flatMap(StreamDemo::filterCharacter); + stream2.forEach(System.out::print); + + } + + // 中间操作-排序 + @Test + public void test3() { + emps.stream() + .map(Employee::getName) + .sorted() // 排序 + .forEach(System.out::println); + + emps.stream() + .sorted((x, y) -> { + if (x.getAge() == y.getAge()) { + return x.getName().compareTo(y.getName()); + } else { + return Integer.compare(x.getAge(), y.getAge()); + } + }) // 排序 + .forEach(System.out::println); + } + + // 查找与匹配 + @Test + public void test4() { + // 查看每个名字中是否都包含"五" ,这里返回false + boolean b = emps.stream().allMatch((e) -> e.getName().contains("五")); + System.out.println(b); + // 返回第一个 + Optional first = emps.stream().findFirst(); + System.out.println(first.get()); + } + + // 归约 + @Test + public void test5() { + // 从0开始加 ,加到10 + List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Integer sum = list.stream().reduce(0, (x, y) -> x + y); + System.out.println(sum); + + // 求所有员工的薪水总和 + Optional op = emps.stream().map(Employee::getSalary).reduce(Double::sum); + System.out.println(op.get()); + } + + //收集 : 将流转换成其他形式,collect(Collectors.()) + @Test + public void test6() { + List list = emps.stream().map(Employee::getName).collect(Collectors.toList()); + list.forEach(System.out::println); + Set set = emps.stream().map(Employee::getName).collect(Collectors.toSet()); + set.forEach(System.out::println); + + // 薪水求和 + Double sum = emps.stream().collect(Collectors.summingDouble(Employee::getSalary)); + //求平均薪水 + Double avg = emps.stream().collect(Collectors.averagingDouble(Employee::getSalary)); + } + + public static Stream filterCharacter(String str) { + ArrayList list = new ArrayList<>(); + for (Character ch : str.toCharArray()) { + list.add(ch); + } + return list.stream(); + } +} diff --git a/04spring/spring01/src/main/java/org/github/yibing/spring/stream/StreamDemo2.java b/04spring/spring01/src/main/java/org/github/yibing/spring/stream/StreamDemo2.java new file mode 100644 index 00000000..698e2f40 --- /dev/null +++ b/04spring/spring01/src/main/java/org/github/yibing/spring/stream/StreamDemo2.java @@ -0,0 +1,158 @@ +package org.github.yibing.spring.stream; + +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class StreamDemo2 { + static List emps = Arrays.asList(new Employee(101, "张三", 28, 9999d), + new Employee(101, "李四", 49, 666d), + new Employee(102, "王五", 38, 333d), + new Employee(103, "赵六", 12, 7777d), + new Employee(104, "田七", 6, 222d) + ); + + public static void main(String[] args) { + /* + * 创建stream的三种方式 + */ + //1.集合 list.stream(), + Stream stream = emps.stream(); + Employee[] array = (Employee[]) emps.toArray(); + // 2.数组 Arrays.stream(array) + Stream stream1 = Arrays.stream(array); + // 3.Stream.of(T) + Stream> stream2 = Stream.of(StreamDemo2.emps); + + + } + + /** + * 中间操作: + * 筛选 filter() + * 去重 distinct() + * 取前面几条/跳过前面几条 limit()/skip() + */ + + @Test + public void test1() { + //中间操作------筛选 + emps.stream().filter((e) -> e.getAge() > 30).forEach(e -> System.out.println(e.getAge())); + // 取前面几条 + emps.stream().filter(e -> e.getId() > 101).limit(3).forEach(System.out::println); + // 需要重写hashcode()和equals 才能去重 + emps.stream().distinct().forEach(System.out::println); + } + + /** + * 中间操作: + * 映射,把集合中每个元素按照function映射为对应的类型 + */ + @Test + public void test2() { + // 把每个元素按照function转换成相应类型,输出 还有mapToInteger,mapToLong等方法 + emps.stream().mapToDouble(Employee::getId).forEach(System.out::println); + List strList = Arrays.asList("a", "b", "c", "d"); + /* + flapMap和map,传入同一个返回流的function,flatMap可以把所有流连成一个流 + */ + Stream rStream = strList.stream().flatMap(StreamDemo2::filterCharacter); + rStream.forEach(System.out::println); + + Stream> stream = strList.stream().map(StreamDemo2::filterCharacter); + stream.forEach(sm -> sm.forEach(System.out::print)); + } + + public static Stream filterCharacter(String str) { + List list = new ArrayList<>(); + for (Character ch : str.toCharArray()) { + list.add(ch); + } + return list.stream(); + } + + /** + * 中间操作: + * sorted() 默认顺序排序,引用类型要实现Comparable + * sorted(Comparator comp) 带参数,指定排序规则 + */ + @Test + public void test3() { + // 把每个emps映射为属性:name,组成一个新流,然后按name排序输出 + emps.stream().map(Employee::getName).sorted().forEach(System.out::println); + // 带参数的sorted,按照年龄排序,若相等就比较名字 + emps.stream().sorted((x, y) -> { + if (x.getAge() == y.getAge()) { + return x.getName().compareTo(y.getName()); + } else { + return Integer.compare(x.getAge(), y.getAge()); + } + }).forEach(System.out::println); + } + + + /** + * 终止操作: 查找与匹配,返回boolean + * allMatch(),所有元素都匹配才返回true + * anyMatch(),只要有一个或多个元素匹配就返回true + * noneMatch(),都不匹配就返回true,否则false + */ + @Test + public void test4() { + // 每个员工的名字都包含三 ,才返回true + boolean b = emps.stream().allMatch(e -> e.getName().contains("三")); + System.out.println(b); + boolean b1 = emps.stream().noneMatch(e -> e.getName().contains("九")); + System.out.println(b1); + + } + + /** + * 终止操作:查找与匹配:返回元素 + * findFirst:返回第一个Optional<> + * findAny:返回任意一个元素Optional<> + * count 返回元素个数 + * max 返回最大值 + * min 返回最小值 + */ + + @Test + public void test5() { + Optional first = emps.stream().findFirst(); + System.out.println(first.get()); + long count = emps.stream().count(); + System.out.println(count); + } + + + /** + * 终止操作:规约reduce,将每个元素结合起来,得到一个值 + * reduce(BinaryOperator b) + * reduce(T iden,BinaryOperator b) 返回Optional + */ + @Test + public void test6() { + // 规约,先转化成年龄集合,然后给他们求和 + Optional sum = emps.stream().map(Employee::getAge).reduce(Integer::sum); + System.out.println(sum.get()); + // 从 1 相加,相当于该集合多了一个 1求和 + Integer sum1 = emps.stream().map(Employee::getAge).reduce(1, Integer::sum); + System.out.println(sum1); + } + + /** + * 终止操作:收集 + * 转换成lit、set、Collection + * 求和,求平均数 + */ + @Test + public void test7() { + Set set = emps.stream().collect(Collectors.toSet()); + System.out.println(set); + List list = emps.stream().collect(Collectors.toList()); + Double salarySum = emps.stream().collect(Collectors.summingDouble(Employee::getSalary)); + + } +} diff --git a/04spring/spring01/src/main/resources/application.properties b/04spring/spring01/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/04spring/spring01/src/main/resources/applicationContext.xml b/04spring/spring01/src/main/resources/applicationContext.xml new file mode 100644 index 00000000..f1c9bb52 --- /dev/null +++ b/04spring/spring01/src/main/resources/applicationContext.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/04spring/spring01/src/main/resources/instantiate-type.xml b/04spring/spring01/src/main/resources/instantiate-type.xml new file mode 100644 index 00000000..ed56a6b1 --- /dev/null +++ b/04spring/spring01/src/main/resources/instantiate-type.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/04spring/springboot01/.gitignore b/04spring/springboot01/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/04spring/springboot01/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/04spring/springboot01/pom.xml b/04spring/springboot01/pom.xml new file mode 100644 index 00000000..dedb6402 --- /dev/null +++ b/04spring/springboot01/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.0 + + + com.github.yibing + springboot01 + 0.0.1-SNAPSHOT + springboot01 + Demo project for Spring Boot + + + 1.8 + + + + + example.springboot + example-spring-boot-starter + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/04spring/springboot01/src/main/java/com/github/yibing/springboot01/Springboot01Application.java b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/Springboot01Application.java new file mode 100644 index 00000000..f3fb9a1a --- /dev/null +++ b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/Springboot01Application.java @@ -0,0 +1,23 @@ +package com.github.yibing.springboot01; + +import example.springboot.starter.service.Student; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot01Application implements CommandLineRunner { + + @Autowired + private Student student; + public static void main(String[] args) { + SpringApplication.run(Springboot01Application.class, args); + } + + @Override + public void run(String... args) throws Exception { + student.init(); + System.out.println(student.getId()); + } +} diff --git a/04spring/springboot01/src/main/java/com/github/yibing/springboot01/config/RabbitConfig.java b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/config/RabbitConfig.java new file mode 100644 index 00000000..c2aeca78 --- /dev/null +++ b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/config/RabbitConfig.java @@ -0,0 +1,14 @@ +package com.github.yibing.springboot01.config; + +import org.springframework.amqp.core.Queue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RabbitConfig { + + @Bean + public Queue queue() { + return new Queue("q_test_1"); + } +} diff --git a/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/Consumer.java b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/Consumer.java new file mode 100644 index 00000000..48a24c51 --- /dev/null +++ b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/Consumer.java @@ -0,0 +1,28 @@ +//package com.github.yibing.springboot01.consumer; +// +//import com.github.yibing.springboot01.util.MqConnectionUtil; +//import com.rabbitmq.client.Channel; +//import com.rabbitmq.client.Connection; +//import com.rabbitmq.client.QueueingConsumer; +// +//import java.io.IOException; +// +//public class Consumer { +// public static void main(String[] args) throws IOException, InterruptedException { +// Connection connection = MqConnectionUtil.getConnection(); +// Channel channel = connection.createChannel(); +// // 声明队列 +// channel.queueDeclare("q_test_1", false, false, false, null); +// // 创建消费队列 +// QueueingConsumer consumer = new QueueingConsumer(channel); +// // 消费消息 +// channel.basicConsume("q_test_1", consumer); +// // 转换消费的消息 +// while (true) { +// QueueingConsumer.Delivery delivery = consumer.nextDelivery(); +// String message = new String(delivery.getBody()); +// System.out.println("收到消息:" + message); +// } +// +// } +//} diff --git a/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/ConsumerServiceImpl.java b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/ConsumerServiceImpl.java new file mode 100644 index 00000000..8bc43d7c --- /dev/null +++ b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/ConsumerServiceImpl.java @@ -0,0 +1,14 @@ +package com.github.yibing.springboot01.consumer; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Service; + +@Service("service_1") +@RabbitListener(queues = "q_test_1") +public class ConsumerServiceImpl { + @RabbitHandler + public void getMessage(String message) { + System.out.println("1" + message); + } +} diff --git a/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/ConsumerServiceImpl2.java b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/ConsumerServiceImpl2.java new file mode 100644 index 00000000..2ec35d23 --- /dev/null +++ b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/consumer/ConsumerServiceImpl2.java @@ -0,0 +1,14 @@ +package com.github.yibing.springboot01.consumer; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Service; + +@Service("service_2") +public class ConsumerServiceImpl2 { + @RabbitListener(queues = "q_test_1") + @RabbitHandler + public void getMessage(String message) { + System.out.println("2" + message); + } +} diff --git a/04spring/springboot01/src/main/java/com/github/yibing/springboot01/controller/ProducerController.java b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/controller/ProducerController.java new file mode 100644 index 00000000..92dd922a --- /dev/null +++ b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/controller/ProducerController.java @@ -0,0 +1,24 @@ +package com.github.yibing.springboot01.controller; + +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.text.SimpleDateFormat; +import java.util.Date; + +@RestController +public class ProducerController { + + @Autowired + private AmqpTemplate amqpTemplate; + + @RequestMapping("/send") + public String send() { + String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + String context = "hello" + date; + amqpTemplate.convertAndSend(context); + return context; + } +} diff --git a/04spring/springboot01/src/main/java/com/github/yibing/springboot01/producer/Producer.java b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/producer/Producer.java new file mode 100644 index 00000000..387e2918 --- /dev/null +++ b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/producer/Producer.java @@ -0,0 +1,22 @@ +//package com.github.yibing.springboot01.producer; +// +//import com.github.yibing.springboot01.util.MqConnectionUtil; +//import com.rabbitmq.client.Channel; +//import com.rabbitmq.client.Connection; +// +//import java.io.IOException; +// +//public class Producer { +// public static void main(String[] args) throws IOException { +// Connection connection = MqConnectionUtil.getConnection(); +// Channel channel = connection.createChannel(); +// // 声明队列 +// channel.queueDeclare("q_test_1", false, false, false, null); +// // 发送消息 +// channel.basicPublish("", "q_test_1", null, "hello a".getBytes()); +// // 关闭通道 +// channel.close(); +// // 关闭通道 +// connection.close(); +// } +//} diff --git a/04spring/springboot01/src/main/java/com/github/yibing/springboot01/util/MqConnectionUtil.java b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/util/MqConnectionUtil.java new file mode 100644 index 00000000..33e21b63 --- /dev/null +++ b/04spring/springboot01/src/main/java/com/github/yibing/springboot01/util/MqConnectionUtil.java @@ -0,0 +1,30 @@ +package com.github.yibing.springboot01.util; + +import java.util.HashMap; + +// +//import com.rabbitmq.client.Connection; +//import com.rabbitmq.client.ConnectionFactory; +// +//import java.io.IOException; +// +public class MqConnectionUtil { +// +// public static Connection getConnection() throws IOException { +// ConnectionFactory factory = new ConnectionFactory(); +// factory.setHost("localhost"); +// factory.setPort(5672); +// factory.setUsername("guest"); +// factory.setPassword("guest"); +// factory.setVirtualHost("testHost"); +// return factory.newConnection(); +// } + + + public static void main(String[] args) { + HashMap hashMap = new HashMap<>(80); + hashMap.put("0",0); + hashMap.put("1",1); + hashMap.put("2",2); + } +} diff --git a/04spring/springboot01/src/main/resources/application.properties b/04spring/springboot01/src/main/resources/application.properties new file mode 100644 index 00000000..94f0a320 --- /dev/null +++ b/04spring/springboot01/src/main/resources/application.properties @@ -0,0 +1,2 @@ +example.student.id=1 +example.student.name=张三 diff --git a/04spring/springboot01/src/main/resources/application.yml b/04spring/springboot01/src/main/resources/application.yml new file mode 100644 index 00000000..26aca95a --- /dev/null +++ b/04spring/springboot01/src/main/resources/application.yml @@ -0,0 +1,7 @@ +spring: + rabbitmq: + host: localhost + password: guest + username: guest + virtual-host: testHost + port: 5672 \ No newline at end of file diff --git a/04spring/springboot01/src/test/java/com/github/yibing/springboot01/Springboot01ApplicationTests.java b/04spring/springboot01/src/test/java/com/github/yibing/springboot01/Springboot01ApplicationTests.java new file mode 100644 index 00000000..986c5174 --- /dev/null +++ b/04spring/springboot01/src/test/java/com/github/yibing/springboot01/Springboot01ApplicationTests.java @@ -0,0 +1,13 @@ +package com.github.yibing.springboot01; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot01ApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/05data/data-demo/.gitignore b/05data/data-demo/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/05data/data-demo/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/05data/data-demo/pom.xml b/05data/data-demo/pom.xml new file mode 100644 index 00000000..2d4d680d --- /dev/null +++ b/05data/data-demo/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.6.RELEASE + + + com.github.yibing.data + data-demo + 0.0.1-SNAPSHOT + data-demo + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + + + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + 8.0.15 + + + org.aspectj + aspectjweaver + 1.9.6 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/DataDemoApplication.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/DataDemoApplication.java new file mode 100644 index 00000000..0b5d05e2 --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/DataDemoApplication.java @@ -0,0 +1,15 @@ +package com.github.yibing.data.datademo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@SpringBootApplication +@EnableAspectJAutoProxy +public class DataDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DataDemoApplication.class, args); + } + +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/annotation/DataSourceAspect.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/annotation/DataSourceAspect.java new file mode 100644 index 00000000..e283c65a --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/annotation/DataSourceAspect.java @@ -0,0 +1,44 @@ +package com.github.yibing.data.datademo.annotation; + +import com.github.yibing.data.datademo.config.DataSourceContextHolder; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.jdbc.datasource.AbstractDataSource; +import org.springframework.stereotype.Component; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedType; +import java.lang.reflect.Method; +import java.sql.Connection; +import java.sql.SQLException; + +@Aspect +@Component +public class DataSourceAspect { + + @Pointcut("@annotation(com.github.yibing.data.datademo.annotation.ReadOnly)") + public void pointcut() { + + } + + @Before("pointcut()") + public void before(JoinPoint joinPoint) { + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + ReadOnly annotation = method.getAnnotation(ReadOnly.class); + if (annotation != null) { + DataSourceContextHolder.switchDataSource(annotation.name()); + } + Annotation[] annotations = joinPoint.getTarget().getClass().getAnnotations(); + System.out.println(annotations); + } + + @After("pointcut()") + public void after() { + DataSourceContextHolder.clear(); + } +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/annotation/ReadOnly.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/annotation/ReadOnly.java new file mode 100644 index 00000000..4521bf2a --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/annotation/ReadOnly.java @@ -0,0 +1,12 @@ +package com.github.yibing.data.datademo.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 ReadOnly { + String name() default "slave"; +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/DataSourceConfig.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/DataSourceConfig.java new file mode 100644 index 00000000..8382c5e3 --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/DataSourceConfig.java @@ -0,0 +1,44 @@ +package com.github.yibing.data.datademo.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + +@Configuration +public class DataSourceConfig { + + @Bean("master") + @ConfigurationProperties("spring.datasource.master") + public DataSource masterDataSource() { + return DataSourceBuilder.create().build(); + } + + @Bean("slave") + @ConfigurationProperties("spring.datasource.slave") + public DataSource slaveDataSource() { + return DataSourceBuilder.create().build(); + } + + @Bean + public RoutingDataSource routingDataSource() { + Map dataSources = new HashMap<>(); + dataSources.put("master", masterDataSource()); + dataSources.put("slave", slaveDataSource()); + RoutingDataSource routingDataSource = new RoutingDataSource(); + routingDataSource.setTargetDataSources(dataSources); + routingDataSource.setDefaultTargetDataSource(dataSources.get("master")); + return routingDataSource; + } + + @Bean + public JdbcTemplate jdbcTemplate() { + return new JdbcTemplate(routingDataSource()); + } + +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/DataSourceContextHolder.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/DataSourceContextHolder.java new file mode 100644 index 00000000..2cb7909a --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/DataSourceContextHolder.java @@ -0,0 +1,22 @@ +package com.github.yibing.data.datademo.config; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class DataSourceContextHolder { + + private static ThreadLocal dataSourceContext = new ThreadLocal<>(); + + public static void switchDataSource(String source) { + log.info("切换数据源为:" + source); + dataSourceContext.set(source); + } + + public static String getDataSource() { + return dataSourceContext.get(); + } + + public static void clear() { + dataSourceContext.remove(); + } +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/RoutingDataSource.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/RoutingDataSource.java new file mode 100644 index 00000000..9bae2ccd --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/config/RoutingDataSource.java @@ -0,0 +1,10 @@ +package com.github.yibing.data.datademo.config; + +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +public class RoutingDataSource extends AbstractRoutingDataSource { + @Override + protected Object determineCurrentLookupKey() { + return DataSourceContextHolder.getDataSource(); + } +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/controller/OrderController.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/controller/OrderController.java new file mode 100644 index 00000000..d5e62fdb --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/controller/OrderController.java @@ -0,0 +1,21 @@ +package com.github.yibing.data.datademo.controller; + +import com.github.yibing.data.datademo.entity.Order; +import com.github.yibing.data.datademo.service.OrderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +public class OrderController { + + @Autowired + private OrderService orderService; + + @GetMapping("/order/query") + public List getOrderList() { + return orderService.queryOrder(); + } +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/entity/Order.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/entity/Order.java new file mode 100644 index 00000000..36e19aed --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/entity/Order.java @@ -0,0 +1,17 @@ +package com.github.yibing.data.datademo.entity; + +import lombok.Data; + +import java.util.Date; + +@Data +public class Order { + private String orderId; + private String userId; + private String address; + private double amount; + private int status; + private Date createTime; + private Date updateTime; + private String comment; +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/service/OrderService.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/service/OrderService.java new file mode 100644 index 00000000..a35f8b26 --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/service/OrderService.java @@ -0,0 +1,14 @@ +package com.github.yibing.data.datademo.service; + + +import com.github.yibing.data.datademo.entity.Order; + +import java.util.List; + +public interface OrderService { + + int insertOneOrder(Order order); + int deleteOrder(Order order); + List queryOrder(); + +} diff --git a/05data/data-demo/src/main/java/com/github/yibing/data/datademo/service/OrderServiceImpl.java b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/service/OrderServiceImpl.java new file mode 100644 index 00000000..140d320f --- /dev/null +++ b/05data/data-demo/src/main/java/com/github/yibing/data/datademo/service/OrderServiceImpl.java @@ -0,0 +1,47 @@ +package com.github.yibing.data.datademo.service; + +import com.github.yibing.data.datademo.annotation.ReadOnly; +import com.github.yibing.data.datademo.entity.Order; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class OrderServiceImpl implements OrderService { + + @Autowired + private JdbcTemplate jdbcTemplate; + + + @Override + public int insertOneOrder(Order order) { + return 0; + } + + @Override + public int deleteOrder(Order order) { + return 0; + } + + @Override + @ReadOnly + public List queryOrder() { + String sql = "select * from order_memory limit 10"; + List maps = jdbcTemplate.query(sql, (rs, rowNum) -> { + Order o = new Order(); + o.setOrderId(rs.getString("order_id")); + o.setUserId(rs.getString("user_id")); + o.setAddress(rs.getString("address")); + o.setAmount(rs.getDouble("amount")); + o.setStatus(rs.getInt("status")); + o.setComment(rs.getString("comment")); + o.setCreateTime(rs.getDate("create_time")); + o.setUpdateTime(rs.getDate("update_time")); + return o; + }); + return maps; + } +} diff --git a/05data/data-demo/src/main/resources/application.properties b/05data/data-demo/src/main/resources/application.properties new file mode 100644 index 00000000..c19a4cea --- /dev/null +++ b/05data/data-demo/src/main/resources/application.properties @@ -0,0 +1,9 @@ +# master datasource +spring.datasource.master.jdbcUrl = jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai +spring.datasource.master.driver-class-name =com.mysql.cj.jdbc.Driver +spring.datasource.master.username=root + +# slave datasource +spring.datasource.slave.jdbcUrl = jdbc:mysql://localhost:3316/mall?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai +spring.datasource.slave.driver-class-name= com.mysql.cj.jdbc.Driver +spring.datasource.slave.username=root diff --git a/05data/data-demo/src/test/java/com/github/yibing/data/datademo/DataDemoApplicationTests.java b/05data/data-demo/src/test/java/com/github/yibing/data/datademo/DataDemoApplicationTests.java new file mode 100644 index 00000000..c607ba0c --- /dev/null +++ b/05data/data-demo/src/test/java/com/github/yibing/data/datademo/DataDemoApplicationTests.java @@ -0,0 +1,13 @@ +package com.github.yibing.data.datademo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DataDemoApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/05data/data-demo2/.gitignore b/05data/data-demo2/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/05data/data-demo2/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/05data/data-demo2/pom.xml b/05data/data-demo2/pom.xml new file mode 100644 index 00000000..3e4ddc96 --- /dev/null +++ b/05data/data-demo2/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.0 + + + com.github.yibing.data + data-demo2 + 0.0.1-SNAPSHOT + data-demo2 + Demo project for Spring Boot + + + 1.8 + 4.1.1 + + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.1.4 + + + + mysql + mysql-connector-java + 5.1.49 + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + + + + + + + + + org.apache.shardingsphere + shardingsphere-jdbc-core-spring-boot-starter + 5.0.0-alpha + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/DataDemo2Application.java b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/DataDemo2Application.java new file mode 100644 index 00000000..a6714d31 --- /dev/null +++ b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/DataDemo2Application.java @@ -0,0 +1,15 @@ +package com.github.yibing.data.datademo2; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@MapperScan("com.github.yibing.data.datademo2.dao") +public class DataDemo2Application { + + public static void main(String[] args) { + SpringApplication.run(DataDemo2Application.class, args); + } + +} diff --git a/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/controller/ProductController.java b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/controller/ProductController.java new file mode 100644 index 00000000..bb0dbbca --- /dev/null +++ b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/controller/ProductController.java @@ -0,0 +1,24 @@ +package com.github.yibing.data.datademo2.controller; + +import com.github.yibing.data.datademo2.entity.Product; +import com.github.yibing.data.datademo2.service.ProductService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +public class ProductController { + @Autowired + private ProductService productService; + + @GetMapping("/product/queryAll") + public List listProducts(){ + return productService.listProducts(); + } + + @PostMapping("/product/save") + public int saveProduct(@RequestBody Product product){ + return productService.save(product); + } +} diff --git a/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/dao/ProductMapper.java b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/dao/ProductMapper.java new file mode 100644 index 00000000..8196866e --- /dev/null +++ b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/dao/ProductMapper.java @@ -0,0 +1,13 @@ +package com.github.yibing.data.datademo2.dao; + +import com.github.yibing.data.datademo2.entity.Product; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface ProductMapper { + List listProducts(); + + int insert(Product product); +} diff --git a/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/entity/Product.java b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/entity/Product.java new file mode 100644 index 00000000..acdcdbb4 --- /dev/null +++ b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/entity/Product.java @@ -0,0 +1,17 @@ +package com.github.yibing.data.datademo2.entity; + +import lombok.Data; + +import java.util.Date; + +@Data +public class Product { + private String productId; + private double price; + private String productName; + private Date createTime; + private Date updateTime; + private String description; + private String productType; + private Integer status; +} diff --git a/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/service/ProductService.java b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/service/ProductService.java new file mode 100644 index 00000000..bc1d8bcf --- /dev/null +++ b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/service/ProductService.java @@ -0,0 +1,12 @@ +package com.github.yibing.data.datademo2.service; + +import com.github.yibing.data.datademo2.entity.Product; + +import java.util.List; + +public interface ProductService { + + List listProducts(); + + int save(Product product); +} diff --git a/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/service/ProductServiceImpl.java b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/service/ProductServiceImpl.java new file mode 100644 index 00000000..7f54da21 --- /dev/null +++ b/05data/data-demo2/src/main/java/com/github/yibing/data/datademo2/service/ProductServiceImpl.java @@ -0,0 +1,25 @@ +package com.github.yibing.data.datademo2.service; + +import com.github.yibing.data.datademo2.dao.ProductMapper; +import com.github.yibing.data.datademo2.entity.Product; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +@Service +public class ProductServiceImpl implements ProductService { + + @Resource + private ProductMapper productMapper; + + @Override + public List listProducts() { + return productMapper.listProducts(); + } + + @Override + public int save(Product product) { + return productMapper.insert(product); + } +} diff --git a/05data/data-demo2/src/main/resources/application.yml b/05data/data-demo2/src/main/resources/application.yml new file mode 100644 index 00000000..6b3748cc --- /dev/null +++ b/05data/data-demo2/src/main/resources/application.yml @@ -0,0 +1,46 @@ +spring: + shardingsphere: + datasource: + common: + type: com.zaxxer.hikari.HikariDataSource + driver-class-name: com.mysql.jdbc.Driver + username: root + names: master,slave1,slave2 + master: + jdbcUrl: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai + slave1: + jdbcUrl: jdbc:mysql://localhost:3316/mall?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai + slave2: + jdbcUrl: jdbc:mysql://localhost:3317/mall?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai + props: + sql: + show: true + enabled: true + rules: + replica-query: + load-balancers: + round-robin: + type: ROUND_ROBIN + props: + workid: 123 + datasources: + ps_ds: + primary-data-source-name: master + replica-data-source-names: slave1,slave2 + load-balancer-name: round_robin + jackson: + time-zone: GMT+8 + date-format: yyyy-MM-dd HH:mm:ss + + +mybatis: + configuration: + map-underscore-to-camel-case: true + type-aliases-package: com.github.yibing.data.datademo2.entity + mapper-locations: classpath:dao/*.xml +server: + port: 8086 +logging: + level: + com.github.yibing.data.datademo2: debug + diff --git a/05data/data-demo2/src/main/resources/dao/ProcuctMapper.xml b/05data/data-demo2/src/main/resources/dao/ProcuctMapper.xml new file mode 100644 index 00000000..350a62d6 --- /dev/null +++ b/05data/data-demo2/src/main/resources/dao/ProcuctMapper.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + insert into product(product_id,price,product_name,create_time,update_time,description,product_type,status) + values(#{productId},#{price},#{productName},#{createTime},#{updateTime},#{description},#{productType},#{status}) + + + \ No newline at end of file diff --git a/05data/data-demo2/src/test/java/com/github/yibing/data/datademo2/DataDemo2ApplicationTests.java b/05data/data-demo2/src/test/java/com/github/yibing/data/datademo2/DataDemo2ApplicationTests.java new file mode 100644 index 00000000..74ceff36 --- /dev/null +++ b/05data/data-demo2/src/test/java/com/github/yibing/data/datademo2/DataDemo2ApplicationTests.java @@ -0,0 +1,13 @@ +package com.github.yibing.data.datademo2; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DataDemo2ApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/05data/data-demo3/pom.xml b/05data/data-demo3/pom.xml new file mode 100644 index 00000000..44045834 --- /dev/null +++ b/05data/data-demo3/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + org.example + data-demo3 + 1.0-SNAPSHOT + + + 8 + 8 + 5.0.0.RELEASE + + + + + mysql + mysql-connector-java + 5.1.49 + + + org.springframework.boot + spring-boot-starter + 2.4.0 + + + org.springframework.boot + spring-boot-starter-web + 2.4.0 + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.1.4 + + + org.projectlombok + lombok + 1.18.16 + + + org.springframework.boot + spring-boot-starter-test + 2.4.0 + + + + \ No newline at end of file diff --git a/05data/data-demo3/src/main/java/org/database/demo/Application.java b/05data/data-demo3/src/main/java/org/database/demo/Application.java new file mode 100644 index 00000000..04df661e --- /dev/null +++ b/05data/data-demo3/src/main/java/org/database/demo/Application.java @@ -0,0 +1,13 @@ +package org.database.demo; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@MapperScan(basePackages = "org.database.demo.dao") +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class,args); + } +} diff --git a/05data/data-demo3/src/main/java/org/database/demo/dao/OrderDao.java b/05data/data-demo3/src/main/java/org/database/demo/dao/OrderDao.java new file mode 100644 index 00000000..04e8373d --- /dev/null +++ b/05data/data-demo3/src/main/java/org/database/demo/dao/OrderDao.java @@ -0,0 +1,17 @@ +package org.database.demo.dao; + +import org.database.demo.entity.Order; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.List; + +@Repository +public interface OrderDao { + + int insertOne(Order order); + + List> query(HashMap condition); + + int update(Order order); +} diff --git a/05data/data-demo3/src/main/java/org/database/demo/entity/Order.java b/05data/data-demo3/src/main/java/org/database/demo/entity/Order.java new file mode 100644 index 00000000..33c7bf61 --- /dev/null +++ b/05data/data-demo3/src/main/java/org/database/demo/entity/Order.java @@ -0,0 +1,24 @@ +package org.database.demo.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Order { + private Integer id; + private Integer userId; + private String commodities; + private Integer status; + private String deliverStatus; + private Integer totalPrice; + private Integer createTime; + private Integer updateTime; + + public Order(Integer id, Integer userId) { + this.id = id; + this.userId = userId; + } +} diff --git a/05data/data-demo3/src/main/java/org/database/demo/utils/JdbcTest.java b/05data/data-demo3/src/main/java/org/database/demo/utils/JdbcTest.java new file mode 100644 index 00000000..708548d3 --- /dev/null +++ b/05data/data-demo3/src/main/java/org/database/demo/utils/JdbcTest.java @@ -0,0 +1,62 @@ +package org.database.demo.utils; + +import java.sql.*; +import java.util.Objects; +import java.util.UUID; +import java.util.stream.IntStream; + +public class JdbcTest { + private static String driver = "com.mysql.jdbc.Driver"; + private static String url = "jdbc:mysql://localhost:3307/sharding_db?useUnicode=true&characterEncoding=utf-8&useServerPrepStmts=true&cachePrepStmts=true"; + private static String username = "root"; + private static String password = "root"; + + public static void insertUsePrepare() throws SQLException { + long start = System.currentTimeMillis(); + for (int i = 0; i < 1000; i++) { + String sql = "insert into t_order (user_id,commodities,status,deliver_status,total_price,create_time,update_time)" + + "values ("; + String[] strings = UUID.randomUUID().toString().split("-"); + sql = sql+(i)+",'"+strings[0]+"',"+(i+1)+",'"+strings[2]+"',"+(i+2)+","+(i+3)+","+(i+4)+")"; + Objects.requireNonNull(getConn()).createStatement().execute(sql); + } + long end = System.currentTimeMillis(); + System.out.println("方式一耗时:" + (end-start)); + } + + public static void insertUsePrepareBatch() throws SQLException { + long start = System.currentTimeMillis(); + String sql = "insert into orders (user_id,commodities,status,deliver_status,total_price,create_time,update_time)" + + "values (?,?,?,?,?,?,?)"; + + PreparedStatement prepareStatement = Objects.requireNonNull(getConn()).prepareStatement(sql); + for (int i = 0; i < 1000000; i++) { + String[] strings = UUID.randomUUID().toString().split("-"); + prepareStatement.setInt(1,i); + prepareStatement.setString(2,strings[0]); + prepareStatement.setInt(3,i+1); + prepareStatement.setString(4,strings[0]); + prepareStatement.setInt(5,i+2); + prepareStatement.setInt(6,i+3); + prepareStatement.setInt(7,i+4); + prepareStatement.addBatch(); + } + prepareStatement.execute(); + long end = System.currentTimeMillis(); + System.out.println("方式一耗时:" + (end-start)); + } + + private static Connection getConn() { + try { + Class.forName(driver); + return DriverManager.getConnection(url, username, password); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static void main(String[] args) throws SQLException { + insertUsePrepare(); + } +} diff --git a/05data/data-demo3/src/main/resources/application.properties b/05data/data-demo3/src/main/resources/application.properties new file mode 100644 index 00000000..3c87d69b --- /dev/null +++ b/05data/data-demo3/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://localhost:3307/sharding_db?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true +spring.datasource.password=root +spring.datasource.username=root + +mybatis.mapper-locations=classpath:mapper/*.xml +mybatis.type-aliases-package=org.database.demo.entity + diff --git a/05data/data-demo3/src/main/resources/mapper/OrderMapper.xml b/05data/data-demo3/src/main/resources/mapper/OrderMapper.xml new file mode 100644 index 00000000..d3090f24 --- /dev/null +++ b/05data/data-demo3/src/main/resources/mapper/OrderMapper.xml @@ -0,0 +1,32 @@ + + + + + id,user_id + + + insert into t_order (id,user_id) values (#{id},#{userId}) + + + update t_order set + + + id = #{id} + + + and user_id = #{user_id} + + + + + \ No newline at end of file diff --git a/05data/data-demo3/src/main/resources/mybatis-config.xml b/05data/data-demo3/src/main/resources/mybatis-config.xml new file mode 100644 index 00000000..3544795f --- /dev/null +++ b/05data/data-demo3/src/main/resources/mybatis-config.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/05data/data-demo3/src/test/java/org/database/demo/dao/OrderTest.java b/05data/data-demo3/src/test/java/org/database/demo/dao/OrderTest.java new file mode 100644 index 00000000..314c9422 --- /dev/null +++ b/05data/data-demo3/src/test/java/org/database/demo/dao/OrderTest.java @@ -0,0 +1,36 @@ +package org.database.demo.dao; + +import org.database.demo.dao.OrderDao; +import org.database.demo.entity.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.internal.matchers.Or; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.HashMap; +import java.util.List; + +@SpringBootTest +@ExtendWith(SpringExtension.class) +@MapperScan(basePackages = "org.database.demo.dao") +public class OrderTest { + + @Autowired + private OrderDao orderDao; + + @Test + public void test(){ +// Order order = new Order(1, 2); +// int num = orderDao.insertOne(order); + + HashMap condition = new HashMap<>(1); + condition.put("user_id",1); + List> list = orderDao.query(condition); + list.forEach(System.out::println); + Order order = new Order(1, 3); + int num1 = orderDao.update(order); + } +} diff --git a/05data/data-demo3/target/classes/application.properties b/05data/data-demo3/target/classes/application.properties new file mode 100644 index 00000000..3c87d69b --- /dev/null +++ b/05data/data-demo3/target/classes/application.properties @@ -0,0 +1,8 @@ +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://localhost:3307/sharding_db?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true +spring.datasource.password=root +spring.datasource.username=root + +mybatis.mapper-locations=classpath:mapper/*.xml +mybatis.type-aliases-package=org.database.demo.entity + diff --git a/05data/data-demo3/target/classes/mapper/OrderMapper.xml b/05data/data-demo3/target/classes/mapper/OrderMapper.xml new file mode 100644 index 00000000..4f947e67 --- /dev/null +++ b/05data/data-demo3/target/classes/mapper/OrderMapper.xml @@ -0,0 +1,21 @@ + + + + + id,user_id + + + insert into t_order (id,user_id) values (#{id},#{userId}) + + + \ No newline at end of file diff --git a/05data/data-demo3/target/classes/mybatis-config.xml b/05data/data-demo3/target/classes/mybatis-config.xml new file mode 100644 index 00000000..3544795f --- /dev/null +++ b/05data/data-demo3/target/classes/mybatis-config.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-hmily-demo/dubbo-account/pom.xml b/dubbo-hmily-demo/dubbo-account/pom.xml new file mode 100644 index 00000000..e8e185ff --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/pom.xml @@ -0,0 +1,27 @@ + + + + dubbo-hmily-demo + io.dobson + 1.0-SNAPSHOT + + 4.0.0 + + io.dobson.account + dubbo-account + + + 8 + 8 + + + + + org.apache.dubbo + dubbo-spring-boot-starter + 2.7.7 + + + \ No newline at end of file diff --git a/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/AccountApplication.java b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/AccountApplication.java new file mode 100644 index 00000000..92f4f38e --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/AccountApplication.java @@ -0,0 +1,14 @@ +package io.dobson.account; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AccountApplication { + public static void main(String[] args) { + SpringApplication springApplication = new SpringApplication(AccountApplication.class); + springApplication.setWebApplicationType(WebApplicationType.NONE); + springApplication.run(args); + } +} diff --git a/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/entity/AccountInfo.java b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/entity/AccountInfo.java new file mode 100644 index 00000000..cbc594f1 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/entity/AccountInfo.java @@ -0,0 +1,20 @@ +package io.dobson.account.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +@Builder +@AllArgsConstructor +@Data +public class AccountInfo implements Serializable { + private Integer id; + private Long accountId; + private Long usd_balance; + private Long rmb_balance; + private Date updateTime; + +} diff --git a/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/mapper/AccountInfoMapper.java b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/mapper/AccountInfoMapper.java new file mode 100644 index 00000000..2a94027e --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/mapper/AccountInfoMapper.java @@ -0,0 +1,12 @@ +package io.dobson.account.mapper; + +import io.dobson.account.entity.AccountInfo; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Update; + +@Mapper +public interface AccountInfoMapper { + @Update("update account_info set usd_balance = usd_balance + #{usd_balance}, rmb_balance = rmb_balance + #{rmb_balance}" + + " where usd_balance >= #{usd_balance} and rmb_balance >= #{rmb_balance} and id = #{id}") + boolean exchange(AccountInfo accountInfo); +} diff --git a/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/service/AccountService.java b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/service/AccountService.java new file mode 100644 index 00000000..be133cb3 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/service/AccountService.java @@ -0,0 +1,9 @@ +package io.dobson.account.service; + +import io.dobson.account.entity.AccountInfo; +import org.dromara.hmily.annotation.Hmily; + +public interface AccountService { + @Hmily + boolean pay(AccountInfo accountInfo); +} diff --git a/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/service/impl/AccountServiceImpl.java b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/service/impl/AccountServiceImpl.java new file mode 100644 index 00000000..29b69ee5 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/src/main/java/io/dobson/account/service/impl/AccountServiceImpl.java @@ -0,0 +1,34 @@ +package io.dobson.account.service.impl; + +import io.dobson.account.entity.AccountInfo; +import io.dobson.account.mapper.AccountInfoMapper; +import io.dobson.account.service.AccountService; +import lombok.extern.slf4j.Slf4j; +import org.apache.dubbo.config.annotation.DubboService; +import org.dromara.hmily.annotation.HmilyTCC; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service +@DubboService(version = "1.0.0") +@Slf4j +public class AccountServiceImpl implements AccountService { + + @Resource + private AccountInfoMapper accountInfoMapper; + + @Override + @HmilyTCC(confirmMethod = "confirmMethod", cancelMethod = "cancelMethod") + public boolean pay(AccountInfo accountInfo) { + return accountInfoMapper.exchange(accountInfo); + } + + public void confirmMethod (){ + log.info("confirm 交易操作================"); + } + + public void cancelMethod(){ + log.info("cancel 交易操作=================="); + } +} diff --git a/dubbo-hmily-demo/dubbo-account/src/main/resources/application.yml b/dubbo-hmily-demo/dubbo-account/src/main/resources/application.yml new file mode 100644 index 00000000..209df722 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/src/main/resources/application.yml @@ -0,0 +1,25 @@ +server: + port: 7001 +spring: + datasource: + driver-class-name: com.mysql.jdbc.Driver + url: jdbc:mysql://127.0.0.1:3311/account_a?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false + username: root + password: root + +dubbo: + application: + name: dubbo-provider + scan: + base-packages: io.dobson.account + registry: + address: zookeeper://localhost:2181 + protocol: + name: dubbo + port: 12345 + metadata-report: + address: zookeeper://localhost:2181 + +mybatis: + type-aliases-package: io.dobson.account.entity + mapper-locations: classpath:mapper/*.xml \ No newline at end of file diff --git a/dubbo-hmily-demo/dubbo-account/src/main/resources/hmily.yml b/dubbo-hmily-demo/dubbo-account/src/main/resources/hmily.yml new file mode 100644 index 00000000..18136626 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/src/main/resources/hmily.yml @@ -0,0 +1,75 @@ +hmily: + server: + configMode: local + appName: account-demo + # 如果server.configMode eq local 的时候才会读取到这里的配置信息. + config: + appName: account-demo + serializer: kryo + contextTransmittalMode: threadLocal + scheduledThreadMax: 16 + scheduledRecoveryDelay: 60 + scheduledCleanDelay: 60 + scheduledPhyDeletedDelay: 600 + scheduledInitDelay: 30 + recoverDelayTime: 60 + cleanDelayTime: 180 + limit: 200 + retryMax: 10 + bufferSize: 8192 + consumerThreads: 16 + asyncRepository: true + autoSql: true + phyDeleted: true + storeDays: 3 + repository: mysql + +repository: + database: + driverClassName: com.mysql.jdbc.Driver + url : jdbc:mysql://127.0.0.1:3311/hmily?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false + username: root + password: root + maxActive: 20 + minIdle: 10 + connectionTimeout: 30000 + idleTimeout: 600000 + maxLifetime: 1800000 + file: + path: + prefix: /hmily + zookeeper: + host: localhost:2181 + sessionTimeOut: 1000 + rootPath: /hmily + redis: + cluster: false + sentinel: false + clusterUrl: + sentinelUrl: + masterName: + hostName: + port: + password: + maxTotal: 8 + maxIdle: 8 + minIdle: 2 + maxWaitMillis: -1 + minEvictableIdleTimeMillis: 1800000 + softMinEvictableIdleTimeMillis: 1800000 + numTestsPerEvictionRun: 3 + testOnCreate: false + testOnBorrow: false + testOnReturn: false + testWhileIdle: false + timeBetweenEvictionRunsMillis: -1 + blockWhenExhausted: true + timeOut: 1000 + +metrics: + metricsName: prometheus + host: + port: 9081 + async: true + threadCount : 16 + jmxConfig: \ No newline at end of file diff --git a/dubbo-hmily-demo/dubbo-account/src/main/resources/mybatis/mybatis-config.xml b/dubbo-hmily-demo/dubbo-account/src/main/resources/mybatis/mybatis-config.xml new file mode 100644 index 00000000..bf8f188c --- /dev/null +++ b/dubbo-hmily-demo/dubbo-account/src/main/resources/mybatis/mybatis-config.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-hmily-demo/dubbo-transaction/pom.xml b/dubbo-hmily-demo/dubbo-transaction/pom.xml new file mode 100644 index 00000000..cfe1bab5 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-transaction/pom.xml @@ -0,0 +1,28 @@ + + + + dubbo-hmily-demo + io.dobson + 1.0-SNAPSHOT + + 4.0.0 + + io.dobson.transaction + dubbo-tranaction + + + 8 + 8 + + + + + io.dobson.account + dubbo-account + 1.0-SNAPSHOT + + + + \ No newline at end of file diff --git a/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/TransactionApplication.java b/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/TransactionApplication.java new file mode 100644 index 00000000..1633d16e --- /dev/null +++ b/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/TransactionApplication.java @@ -0,0 +1,25 @@ +package io.dobson.transaction; + +import io.dobson.transaction.service.TransactionService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TransactionApplication implements ApplicationRunner { + @Autowired + private TransactionService transactionService; + + public static void main(String[] args) { + SpringApplication springApplication = new SpringApplication(TransactionApplication.class); + springApplication.setWebApplicationType(WebApplicationType.NONE); + springApplication.run(args); + } + @Override + public void run(ApplicationArguments args) throws Exception { + transactionService.pay(); + } +} diff --git a/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/service/TransactionService.java b/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/service/TransactionService.java new file mode 100644 index 00000000..a0f8a62b --- /dev/null +++ b/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/service/TransactionService.java @@ -0,0 +1,8 @@ +package io.dobson.transaction.service; + +import org.dromara.hmily.annotation.Hmily; + +public interface TransactionService { + @Hmily + void pay(); +} diff --git a/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/service/impl/TransactionServiceImpl.java b/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/service/impl/TransactionServiceImpl.java new file mode 100644 index 00000000..a4b5db55 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-transaction/src/main/java/io/dobson/transaction/service/impl/TransactionServiceImpl.java @@ -0,0 +1,42 @@ +package io.dobson.transaction.service.impl; + +import io.dobson.account.entity.AccountInfo; +import io.dobson.account.service.AccountService; +import io.dobson.transaction.service.TransactionService; +import lombok.extern.slf4j.Slf4j; +import org.apache.dubbo.config.annotation.DubboReference; +import org.dromara.hmily.annotation.HmilyTCC; +import org.springframework.stereotype.Service; + +@Service +@Slf4j +public class TransactionServiceImpl implements TransactionService { + + @DubboReference(version = "1.0.0") + private AccountService accountService; + + @Override + @HmilyTCC(confirmMethod = "confirmMethod", cancelMethod = "cancelMethod") + public void pay() { + transactionA(); + transactionB(); + } + + private void transactionB() { + AccountInfo account = AccountInfo.builder().id(2).rmb_balance(7L).usd_balance(-1L).build(); + accountService.pay(account); + } + + private void transactionA() { + AccountInfo account = AccountInfo.builder().id(1).rmb_balance(-7L).usd_balance(1L).build(); + accountService.pay(account); + } + + public void confirmMethod() { + log.info("confirm method invoked"); + } + + public void cancelMethod() { + log.info("cancel method invoked"); + } +} diff --git a/dubbo-hmily-demo/dubbo-transaction/src/main/resources/application.yml b/dubbo-hmily-demo/dubbo-transaction/src/main/resources/application.yml new file mode 100644 index 00000000..6febd924 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-transaction/src/main/resources/application.yml @@ -0,0 +1,18 @@ +spring: + datasource: + driver-class-name: com.mysql.jdbc.Driver + url: jdbc:mysql://127.0.0.1:3311/account_a?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false + username: root + password: root +server: + port: 7002 + +dubbo: + application: + name: dubbo-consumer + scan: + base-packages: io.dobson.transaction + registry: + address: zookeeper://localhost:2181 + metadata-report: + address: zookeeper://localhost:2181 diff --git a/dubbo-hmily-demo/dubbo-transaction/src/main/resources/hmily.yml b/dubbo-hmily-demo/dubbo-transaction/src/main/resources/hmily.yml new file mode 100644 index 00000000..6951ad62 --- /dev/null +++ b/dubbo-hmily-demo/dubbo-transaction/src/main/resources/hmily.yml @@ -0,0 +1,75 @@ +hmily: + server: + configMode: local + appName: transaction-demo + # 如果server.configMode eq local 的时候才会读取到这里的配置信息. + config: + appName: transaction-demo + serializer: kryo + contextTransmittalMode: threadLocal + scheduledThreadMax: 16 + scheduledRecoveryDelay: 60 + scheduledCleanDelay: 60 + scheduledPhyDeletedDelay: 600 + scheduledInitDelay: 30 + recoverDelayTime: 60 + cleanDelayTime: 180 + limit: 200 + retryMax: 10 + bufferSize: 8192 + consumerThreads: 16 + asyncRepository: true + autoSql: true + phyDeleted: true + storeDays: 3 + repository: mysql + +repository: + database: + driverClassName: com.mysql.jdbc.Driver + url : jdbc:mysql://127.0.0.1:3311/hmily?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false + username: root + password: root + maxActive: 20 + minIdle: 10 + connectionTimeout: 30000 + idleTimeout: 600000 + maxLifetime: 1800000 + file: + path: + prefix: /hmily + zookeeper: + host: localhost:2181 + sessionTimeOut: 1000 + rootPath: /hmily + redis: + cluster: false + sentinel: false + clusterUrl: + sentinelUrl: + masterName: + hostName: + port: + password: + maxTotal: 8 + maxIdle: 8 + minIdle: 2 + maxWaitMillis: -1 + minEvictableIdleTimeMillis: 1800000 + softMinEvictableIdleTimeMillis: 1800000 + numTestsPerEvictionRun: 3 + testOnCreate: false + testOnBorrow: false + testOnReturn: false + testWhileIdle: false + timeBetweenEvictionRunsMillis: -1 + blockWhenExhausted: true + timeOut: 1000 + +metrics: + metricsName: prometheus + host: + port: 9091 + async: true + threadCount : 16 + jmxConfig: \ No newline at end of file diff --git a/dubbo-hmily-demo/pom.xml b/dubbo-hmily-demo/pom.xml new file mode 100644 index 00000000..a891d124 --- /dev/null +++ b/dubbo-hmily-demo/pom.xml @@ -0,0 +1,126 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.0.RELEASE + + io.dobson + dubbo-hmily-demo + pom + 1.0-SNAPSHOT + + dubbo-account + dubbo-transaction + + + + 8 + 8 + 2.3.0.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + + + + org.apache.dubbo + dubbo + 2.7.7 + + + org.apache.dubbo + dubbo-dependencies-zookeeper + 2.7.7 + pom + + + org.slf4j + slf4j-log4j12 + + + + + + org.dromara + hmily-spring-boot-starter-apache-dubbo + 2.1.1 + + + org.dromara + hmily-repository-mongodb + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + log4j + log4j + + + + + org.projectlombok + lombok + 1.18.16 + + + + mysql + mysql-connector-java + 5.1.49 + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.1.4 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + \ No newline at end of file