SpringCloud案例day01.md

SpringCloudDemos

添加springcloud父工程配置

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dev1</groupId>
    <artifactId>SpringCloudDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 继承父工程 springcloud依赖springboot-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <!--    utf-8配置与jdk版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <!--    需要添加哪些依赖,springboot-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <!--    添加springcloud-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>http://repo.spring.io/libs-release-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

搭建Eureka

1 搭建Eureka注册中心

注意所有的服务名中不出现下划线,必须使用中划线
(1) SpringCloudDemo下创建Eureaka-Center9000子模块
在 SpringCloudDemo 下创建子模块Eureaka-Center9000
(2) 引入maven坐标

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

(3) 配置application.yml

#EurekaServer端口9000
spring:
  application:
    name: Eureaka-Center9000
server:
  port: 9000 #端口 决定后面的管理页面也使用9000端口
#配置eureka server
eureka:
  client:
    register-with-eureka: false #是否将自己注册到注册中心
    fetch-registry: false #是否从eureka中获取注册信息
    service-url: #配置暴露给Eureka Client的请求地址
      defaultZone: http://127.0.0.1:9000/eureka/
  server:
    enable-self-preservation: false #关闭自我保护
    eviction-interval-timer-in-ms: 4000 #剔除服务间隔

registerWithEureka: 是否将自己注册到Eureka服务中,本身就是所有无需注册
fetchRegistry : 是否从Eureka中获取注册信息
serviceUrlEureka: 客户端与Eureka服务端进行交互的地址

(4) 配置启动类
在 com.dev1.eureka 下创建启动类 Center9000
EnableEurekaServer : 激活Eureka Server端配置

@SpringBootApplication
//激活eureakaserver
@EnableEurekaServer
public class Center9000 {
    public static void main(String[] args) {
        SpringApplication.run(Center9000.class,args);
    }
}

(5)服务注册中心管理后台
打开浏览器访问

http://localhost:9000
访问端口由配置文件中的server port决定

即可进入EurekaServer内置的管理控制台,显示效果如下

2 服务A注册到Eureka注册中心

服务A注册
(1) 服务模块中引入坐标
在 Service-A9001 的pom文件中添加eureka client的相关坐标

 <dependencies>
        <!--引入EurekaClient-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

(2) 配置application.yml文件
在工程的 application.yml 中添加Eureka Server的主机地址

server:
  port: 9001
spring:
  application:
    name: Service-A9001
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/

(3) 修改启动类添加服务注册注解
从Spring Cloud Edgware版本开始, @EnableDiscoveryClient 或 @EnableEurekaClient 可省略。只需加上相关依赖,并进行相应配置,即可将微服务注册到服务发现组件上。

@SpringBootApplication
//激活eurekaClient
@EnableEurekaClient
//@EnableDiscoveryClient
public class A9001 {
    public static void main(String[] args) {
        SpringApplication.run(A9001.class,args);
    }
}

3 服务B注册到Eureka注册中心

案例:高可靠性,双注册中心

复制:Eureaka-Center9000,重命名 Eureaka-Center8000

application.yml

spring:
  application:
    name: Eureka-Center
server:
  port: 8000

#配置eureka server
eureka:
  instance:
    prefer-ip-address: true #使用ip地址注册
    instance-id:  ${spring.cloud.client.ip-address}:${server.port}#向注册中心中注册服务id
    lease-renewal-interval-in-seconds: 5 #向注册中心中注册服务id
    lease-expiration-duration-in-seconds: 10 #续约到期的时间
  client:
    register-with-eureka: false #是否将自己注册到注册中心
    fetch-registry: false #是否从eureka中获取注册信息
    service-url: #配置暴露给Eureka Client的请求地址
      defaultZone: http://127.0.0.1:9000/eureka/
  server:
    enable-self-preservation: false #关闭自我保护
    eviction-interval-timer-in-ms: 4000 #剔除服务间隔

机器2
Eureaka-Center9000 application.yml

<pre style="background-color:#ffffff;color:#080808;font-family:'Consolas';font-size:13.5pt;">spring:
  application:
    name: Eureka-Center
server:
  port: 9000

#配置eureka server
eureka:
  instance:
    prefer-ip-address: true #使用ip地址注册
  instance-id:  ${spring.cloud.client.ip-address}:${server.port}#向注册中心中注册服务id
    lease-renewal-interval-in-seconds: 5 #向注册中心中注册服务id
  lease-expiration-duration-in-seconds: 10 #续约到期的时间
  client:
    register-with-eureka: false #是否将自己注册到注册中心
  fetch-registry: false #是否从eureka中获取注册信息
  service-url: #配置暴露给Eureka Client的请求地址
  defaultZone: http://127.0.0.1:8000/eureka/
  server:
    enable-self-preservation: false #关闭自我保护
  eviction-interval-timer-in-ms: 4000 #剔除服务间隔</pre>

即完成互相注册
其他服务需要修改

defaultZone: http://localhost:9000/eureka/,http://localhost:8000/eureka/

案例:消费者

1 ServiceA添加Controller

定义Person类

public class Person {
    private Long id;
    private String name;
    //省略get /set 

编写Controller

@RestController
@RequestMapping("/person")
public class PersonController {

    @RequestMapping(method = RequestMethod.GET,value = "/find/{id}")
    public Person find(@PathVariable Long id){
        Person person = new Person();
        person.setId(id);
        person.setName("我是服务A的根据id查询Person信息");
        return person;
    }
}

2 消费服务A中的数据

(1)在Service-A9001增加业务方法

  @RequestMapping(method = RequestMethod.GET,value = "/findnames")
    public QueryResult findNames(){
        QueryResult qr = new QueryResult();
        //创建名单列表
        List<Person> list = new ArrayList<>();
        //循环添加学生
        for (long i = 0; i < 10; i++) {
            Person person = new Person();
            person.setId(1000+i);
            person.setName("张"+i);
            list.add(person);
        }
        //封装成一个普通对象
        qr.setData(list);
        return qr;
    }

实体类

public class QueryResult {
    private int code = 200;
    private Object data;

(2)创建 Cosumer-C9003

@RestController
@RequestMapping("/idcard")
public class IdCardController {

    @Autowired
    private RestTemplate r ;

    @RequestMapping(method = RequestMethod.GET,value = "/createIdcards")
    public List<String> createIdcards(){
        //访问服务A获取学生的名单列表

        QueryResult qr = r.getForObject("http://localhost:9001/person/findnames", QueryResult.class);
        List<String> list = new ArrayList();
        //把名字取出,名字加上准考证
        List<LinkedHashMap> ps = (List<LinkedHashMap>) qr.getData();
        for(LinkedHashMap p:ps){
            list.add(p.get("name")+"准考证");
        }
        return list;
    }
}

创建RestTemplate

@SpringBootApplication
//激活eurekaClient
@EnableEurekaClient
//@EnableDiscoveryClient
public class C9003 {

    //创建RestTemplate,由@Bean将实例放到spring容器里面
    @Bean
    RestTemplate restTemplate(){
        RestTemplate r = new RestTemplate();
        return r;
    }
    public static void main(String[] args) {
        SpringApplication.run(C9003.class,args);
    }
}

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

翁老师的教学团队

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值