1 Star 0 Fork 0

karidyang / geekbang-lessons-v1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

第二次作业

启动工程,请执行

cd projects/stage-0/user-platform
mvn clean package
java -jar user-web/target/user-web-v1-SNAPSHOT-war-exec.jar

第三次作业

#启动工程
cd projects/stage-0/user-platform
mvn clean package
java -jar user-web/target/user-web-v1-SNAPSHOT-war-exec.jar

#启动工程,并且设置环境变量
java -jar -Dapplication.name=java-user-web user-web/target/user-web-v1-SNAPSHOT-war-exec.jar
  • 文件环境变量 user-web/src/main/resources/META-INF/application.properties

  • 查看MBean http://127.0.0.1:8080/jolokia/read/org.geektimes.projects.user.management:type=User

  • 获取配置的测试在TestingListener类里面

第四次作业

cd projects/stage-0/user-platform
mvn clean package
java -jar user-web/target/user-web-v1-SNAPSHOT-war-exec.jar

第五次作业

  • 需要先启动activemq

  • 修复本程序 org.geektimes.reactive.streams 包下

    已完成

  • 继续完善 my-rest-client POST 方法

    已完成

    • 启动user-web
    cd projects/stage-0/user-platform
    mvn clean package
    java -jar user-web/target/user-web-v1-SNAPSHOT-war-exec.jar
    • 执行 org.geektimes.rest.demo.RestClientDemo.testPostWithEmptyBody 方法

第六次作业

  • 测试类

    org.geektimes.cache.CachingTest#testSampleRedis

    org.geektimes.cache.CachingTest#testSampleRedisWithPojo

  • 序列化实现,实现了String和JSON,Object3种方式

    • org.geektimes.serialize.impl.StringSerializer
    • org.geektimes.serialize.impl.JsonSerializer
    • org.geektimes.serialize.impl.ObjectSerializer

第九次作业

要求

  1. Spring Cache 与 Redis 整合
  • 如何清除某个 Spring Cache 所有的 Keys 关联的对象

    • 如果 Redis 中心化方案,Redis + Sentinel

    • 如果 Redis 去中心化方案,Redis Cluster

  1. 如何将 RedisCacheManager 与 @Cacheable 注解打通

思路

  • 测试类
org.geektimes.projects.user.web.spring.cache.RedisCacheConfigurationDemo
  1. 定义一个自定义的CacheManage
@Bean(name = "customCacheManager")
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager("redis://127.0.0.1:6379/");
        return redisCacheManager;
    }
  1. 在@Cacheable中配置自定义的CacheManager

    @Cacheable(value = "test",key = "#ttt", cacheManager = "customCacheManager")

    这样就实现了RedisCacheManager 与 @Cacheable 注解打通

  2. Redis Cluster去中心划方案

		@Bean(name = "redisClusterCacheManager")
    public RedisClusterCacheManager redisClusterCacheManager() {
        RedisClusterCacheManager redisCacheManager = new RedisClusterCacheManager("redis://192.168.10.100:6379/;redis://192.168.10.101:6379/");
        return redisCacheManager;
    }
  1. Redis Sentinel中心化方案
		@Bean(name = "redisSentinelCacheManager")
    public RedisSentinelCacheManager redisSentinelCacheManager() {
        RedisSentinelCacheManager redisCacheManager = new RedisSentinelCacheManager("mymaster", "192.168.10.100:6379;192.168.10.101:6379");
        return redisCacheManager;
    }
  1. 通过改变@Cachealbe注解中的cacheManager配置,可以使用不同的Redis方案

第十次作业

要求

完善@org.geektimes.projects.user.mybatis.annotation.EnableMyBatis 实现,尽可能多地注入org.mybatis.spring.SqlSessionFactoryBean 中依赖的组件

思路

测试入口类

org.geektimes.projects.user.mybatis.annotation.EnableMyBatisExample
  1. 完善这几个组件

    properties = "META-INF/mybatis/mybatis.properties",
    typeAliases = {User.class},
    typeHandlers = {EmailTypeHandler.class}
    plugins = {MyInterceptor.class}
  2. 启动时需要配置数据库密码

		@Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("12345678");

        return dataSource;
    }
  1. 执行sql
CREATE TABLE users
(
    id          INT         NOT NULL PRIMARY KEY auto_increment,
    name        VARCHAR(16) NOT NULL,
    password    VARCHAR(64) NOT NULL,
    email       VARCHAR(64) NOT NULL,
    phoneNumber VARCHAR(64) NOT NULL
);

INSERT INTO users(name, password, email, phoneNumber)
VALUES ('A', '******', 'a@gmail.com', '1'),
       ('B', '******', 'b@gmail.com', '2'),
       ('C', '******', 'c@gmail.com', '3'),
       ('D', '******', 'd@gmail.com', '4'),
       ('E', '******', 'e@gmail.com', '5');

第十一次作业

要求

  1. 通过 Java 实现两种(以及)更多的一致性 Hash 算法

  2. (可选)实现服务节点动态更新

解答

一致性Hash是为了解决Hash节点更新时,尽量少的变更节点上的数据内容。

  1. 方式1:不带虚拟节点的Hash算法

    org.geektimes.projects.user.dubbo.ConsistentHashingWithoutVirtualNode
  2. 方式2:带虚拟节点的Hash算法

    org.geektimes.projects.user.dubbo.ConsistentHashingWithVirtualNode

第十二次作业

要求

将上次 MyBatis @Enable 模块驱动,封装成 Spring Boot Starter ⽅式

解答

  1. 创建一个新的工程mybatis-spring-starter

  2. 创建引导文件 META-INF/spring.factories,内容如下

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    org.geektimes.projects.mybatis.autoconfiguration.MybatisAutoConfiguration
  3. 新建自动装配类MybatisAutoConfiguration,完成自动装配sqlSessionFactory

  4. user-web工程下新增application.yml文件,内容如下:

    mybatis:
        enabled: true   #是否启用开关
        config-location: META-INF/mybatis/mybatis-config.xml
        data-source: dataSource
        mapper-locations: META-INF/mybatis/mappers/**/*.xml
        properties: META-INF/mybatis/mybatis.properties
        type-aliases: EmailTypeHandler.class
        type-handlers: User.class
    
  5. 修改测试类 org.geektimes.projects.user.mybatis.EnableMyBatisExample,使用SpringBootApplication方式启动。执行main方法,输出查询结果,结果正确,说明starter已经成功。

User{id=1, name='A', password='******', email='a@gmail.com', phoneNumber='null'}
User{id=2, name='B', password='******', email='b@gmail.com', phoneNumber='null'}
User{id=3, name='C', password='******', email='c@gmail.com', phoneNumber='null'}
User{id=4, name='D', password='******', email='d@gmail.com', phoneNumber='null'}
User{id=5, name='E', password='******', email='e@gmail.com', phoneNumber='null'}

第十三次作业

要求

基于文件系统为 Spring Cloud 提供 PropertySourceLocator实现

  • 配置文件命名规则(META-INF/config/default.properties或者 META-INF/config/default.yaml)

  • 可选:实现文件修改通知

解答

  1. pom.xml中增加如下的依赖(Spring Cloud 2020.1必须增加,之前的版本不需要,坑点!)

    <dependency>
    		<groupId>org.springframework.cloud</groupId>
    		<artifactId>spring-cloud-starter-bootstrap</artifactId>
    </dependency>
  2. 实现 PropertySourceLocator -> org.geektimes.projects.spring.cloud.config.client.FileSystemPropertySourceLocator

  3. 读取配置文件目录 META-INF/config/ ,根据profile找到对应的配置文件,可以是properties的,也可以是yaml的,构建PropertySource

  4. 注入测试类 ConfigClient

    		@Value("${user.name}")
        private String userName;
        @Value("${user.age}")
        private int userAge;
    
    		@Bean
        public ApplicationRunner runner() {
            return args -> System.out.printf("user.name = %s, user.age = %d, foo = %s %n", myName, myAge, foo);
        }
    
  5. 实现文件修改通知。利用Java类 WatchService实现文件监听类org.geektimes.projects.spring.cloud.config.client.FileSystemPropertySourceLocator.FileWatch,目前只实现到监听文件变化了,暂时未实现配置刷新。

  6. 启动方式

    1. 启动EurekaServer
    2. 启动ConfigServer
    3. 启动ConfigClient

第十四次作业

要求

利用 Redis 实现 Spring Cloud Bus 中的 BusBridge,避免强依赖于 Spring Cloud Stream

解答

  1. 增加依赖
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-bus</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-redis</artifactId>
            <version>5.4.2</version>
        </dependency>

        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.15.5</version>
        </dependency>

        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </dependency>
  1. 实现了一个自定义的BusBridge
public class RedisBusBridge implements BusBridge {
    private final RedisBridge redisBridge;

    private final BusProperties properties;

    public RedisBusBridge(RedisBridge redisBridge, BusProperties properties) {
        this.redisBridge = redisBridge;
        this.properties = properties;
    }

    public void send(RemoteApplicationEvent event) {
        this.redisBridge.send(properties.getDestination(), MessageBuilder.withPayload(event).build());
    }
}
  1. 实现RedisBridge代替StreamBridge
public class RedisBridge implements SmartInitializingSingleton {
    
}
  1. 实现了一个Binder
org.geektimes.projects.spring.cloud.stream.binder.redis.RedisMessageChannelBinder

发送方

MessageChannel messageChannel = new SubscribableRedisChannel(redisConnectionFactory, "springCloudBus");
        GenericMessage<String> message = new GenericMessage("Hello,World");
        messageChannel.send(message);
        System.out.println("send message=" + message.getPayload());

接收方

	@Bean
    public Consumer<String> message() {
        return message -> {
            System.out.println("Consumer 消息内容:" + message);
        };
    }

配置文件 application.yml

spring:
  application:
    name: spring-cloud-service-consumer
  cloud:
    stream:
      bindings:
        springCloudBusInput:
          destination: springCloudBus
          group: foo

但是目前就只到这里了。。。启动后,能够看到redis里面有队列,但是发送数据不成功。。。

自定义的RedisBusBridge没有生效。

接收方从日志能发现有订阅Redis,但是没有消息。。。

只能交个半成品。。。

第十五次作业

要求

通过 GraalVM 将一个简单 Spring Boot 工程构建为 Native

Image,要求:

  • 代码要自己手写 @Controller

@RequestMapping("/helloworld")

  • 相关插件可以参考 Spring Native Samples

  • (可选)理解 Hint 注解的使用

解答

  • 项目 spring-native

  • 环境准备

    • visual studio 2019

    • wsl2

    • graavlVM

    • 修改系统环境变量

      • setx /M PATH "D:\software\graalvm-ce-java11-21.1.0\bin;%PATH%"
        setx /M JAVA_HOME "D:\software\graalvm-ce-java11-21.1.0"
    • 连maven中央仓库,不要连阿里云,阿里云缺少native的包和插件

  • 执行打包命令

    mvn package -Pnative

    报错:

    [ERROR] Failed to execute goal org.graalvm.nativeimage:native-image-maven-plugin:21.0.0.2:native-image (default) on project demo-spring-native: Could not find executable native-image in D:\software\graalvm-ce-java11-21.1.0\jre\lib\svm\bin\native-image.exe -> [Help 1]

    缺少native-image.exe?这个执行文件是哪里来的呢?

    请安装组件 gu install native-image

  • 启动 target/com.example.springnative.springnativeapplication.exe

  • 访问 http://localhost:8080,页面显示hello.完成

第十六次作业

要求

将 Spring Boot 应用打包 Java Native 应用,再将该应用通过 Dockerfile 构建 Docker 镜像,部署到 Docker 容器中,并且成功运行,Spring Boot 应用的实现复杂度不做要求

解答

在上次的项目中增加 Dockerfile

FROM centos:centos7
#安装maven
RUN mkdir /usr/local/maven
WORKDIR /usr/local/maven/
#从本地复制maven到容器,ADD命令会自动解压
ADD apache-maven-3.8.1-bin.tar.gz /usr/local/maven/
#设置MAVEN_HOME
ENV MAVEN_HOME=/usr/local/maven/apache-maven-3.8.1/

#安装graalvm
RUN	mkdir /usr/local/graalvm
#从本地复制graalvm及native-image到容器
ADD graalvm-ce-java11-linux-amd64-21.1.0.tar.gz /usr/local/graalvm/
ADD native-image-installable-svm-java11-linux-amd64-21.1.0.jar /usr/local/graalvm/
WORKDIR /usr/local/graalvm/
#设置JAVA_HOME
ENV JAVA_HOME=/usr/local/graalvm/graalvm-ce-java11-21.1.0/
#设置PATH
ENV PATH=${JAVA_HOME}/bin:${MAVEN_HOME}/bin:$PATH
#安装native-image
RUN	gu install -L /usr/local/graalvm/native-image-installable-svm-java11-linux-amd64-21.1.0.jar
#安装native-iamge运行时依赖gcc等环境
RUN yum -y install gcc glibc-devel zlib-devel libstdc++-static

#从gitee拉取代码并构建native-image
RUN yum -y install git
WORKDIR /usr/local/
RUN git clone https://gitee.com/karidyang/geekbang-lessons-v1.git
WORKDIR /usr/local/geekbang-lessons-v1/
WORKDIR /usr/local/geekbang-lessons-v1/projects/stage-0/spring-native
RUN mvn -Pnative clean package -Dmaven.test.skip=true
EXPOSE 8080
CMD /usr/local/geekbang-lessons-v1/projects/stage-0/spring-native/target/

执行创建镜像

docker build -t spring-native:v1 .

启动容器

docker run -d -it -p 8080:8080 spring-native

访问 http://localhost:8080/helloworld

注意:

需要将3个本地拷贝到库放到项目文件下

apache-maven-3.8.1-bin.tar.gz
graalvm-ce-java11-linux-amd64-21.1.0.tar.gz
native-image-installable-svm-java11-linux-amd64-21.1.0.jar

下载地址

maven

GraalVM

native-image

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

暂无描述 展开 收起
Java 等 2 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/karidyang/geekbang-lessons-v1.git
git@gitee.com:karidyang/geekbang-lessons-v1.git
karidyang
geekbang-lessons-v1
geekbang-lessons-v1
master

搜索帮助