Spring Cloud微服务教程-第一篇

SpringCloud微服务完整教程 - 电商系统实战 本文提供了一个基于SpringCloud的微服务电商系统完整实现方案。系统采用Nacos作为服务注册中心和配置中心,使用SpringCloud Gateway作为API网关,包含用户、商品、订单等核心业务微服务。关键技术栈包括OpenFeign服务调用、Sentinel服务保护、Seata分布式事务、Sleuth+Zipkin链路追踪以及SpringCloud Bus消息总线。文章详细介绍了系统架构设计、各模块实现方法,并提供了Docker部署方案和最佳实践建议,是一个完整的SpringCloud微服务实战 阅读详情

Spring Cloud微服务教程-第一篇

1.教程大纲
2.统一开发环境
3.微服务架构
4.Spring Cloud简介
5.使用 Spring Boot 实现微服务
6.Spring Cloud快速入门

1.教程大纲
统一开发环境
了解微服务架构
了解Spring Cloud
Spring Cloud快速入门
Eureka服务注册中心
使用Ribbon实现负载均衡
使用Hystrix实现容错
2.统一开发环境
JDK: 1.8
IDE: IntelliJ IDEA
Maven:3.3.9
OS: Windows 10 10.0
Springboot版本:2.0+
3.微服务架构
目前微服务是非常火的架构或者说概念,也是在构建大型互联网项目时采用的架构方式。

3.1.单体架构
单体架构,是指将开发好的项目打成war包,然后发布到tomcat等容器中的应用。

假设你正准备开发一款与Uber和滴滴竞争的出租车调度软件,经过初步会议和需求分析,你可能会手动或者使用基于Spring Boot、Play或者Maven的生成器开始这个新项目,它的六边形架构是模块化的
应用核心是业务逻辑,由定义服务、领域对象和事件的模块完成。围绕着核心的是与外界打交道的适配器。适配器包括数据库访问组件、生产和处理消息的消息组件,以及提供API或者UI访问支持的web模块等。

尽管也是模块化逻辑,但是最终它还是会打包并部署为单体式应用。具体的格式依赖于应用语言和框架。例如,许多Java应用会被打包为WAR格式,部署在Tomcat或者Jetty上,而另外一些Java应用会被打包成自包含的JAR格式,类似的,Rails和Node.js会被打包成层级目录。

这种应用开发风格很常见,因为IDE和其它工具都擅长开发一个简单应用,这类应用也很易于调试,只需要简单运行此应用,用Selenium链接UI就可以完成端到端测试。单体式应用也易于部署,只需要把打包应用拷贝到服务器端,通过在负载均衡器后端运行多个拷贝就可以轻松实现应用扩展。在早期这类应用运行的很好。

3.2.单体架构存在的问题
在这里插入图片描述
在这里插入图片描述
如何解决以上问题呢? – 使用微服务架构。使得应用由重变轻。

3.3.什么是微服务?
在这里插入图片描述
微服务架构的特征
在这里插入图片描述
3.5.微服务架构示例
在这里插入图片描述
每一个应用功能区都使用微服务完成。

4.Spring Cloud简介
4.1.简介
Spring Cloud项目的官方网址:
http://projects.spring.io/spring-cloud/
4.2.Spring Cloud子项目
在这里插入图片描述
4.3.版本说明
在这里插入图片描述
4.4.Spring Cloud框架特点
在这里插入图片描述
5.使用 Spring Boot 实现微服务
在正式学习Spring Cloud之前我们先使用Spring Boot实现一个微服务。

业务非常简单:
1、商品微服务:通过商品id查询商品的服务;
2、订单微服务:创建订单时通时,通过调用商品的微服务进行查询商品数据;

图示:在这里插入图片描述
说明:
1、对于商品微服务而言,商品微服务是服务的提供者,订单微服务是服务的消费者;
2、对于订单微服务而言,订单微服务是服务的提供者,人是服务的消费者。

5.1.实现商品微服务
5.1.1.创建maven工程
地址git:
5.1.2.导入依赖
重点是导入Spring Boot的依赖:

<?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.zpc.microservice</groupId>
    <artifactId>microservice-item</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- 资源文件拷贝插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    </project>
5.1.3.创建实体Item
package com.zpc.item.entity;

public class Item {

    private Long id;

    private String title;

    private String pic;

    private String desc;

    private Long price;

    public Item(){}

    public Item(long id, String title, String pic, String desc, Long price) {
        this.id=id;
        this.title=title;
        this.pic=pic;
        this.desc=desc;
        this.price=price;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Item [id=" + id + ", title=" + title + ", pic=" + pic + ", desc=" + desc + ", price=" + price + "]";
    }

}

5.1.4.编写ItemService
编写ItemService用于实现具体的商品查询逻辑,为了演示方便,我们并不真正的连接数据库,而是做模拟实现。

package com.zpc.item.service;
import com.zpc.item.entity.Item;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
public class ItemService {

    private static final Map<Long, Item> ITEM_MAP = new HashMap<Long, Item>();

    static {// 准备一些静态数据,模拟数据库
        ITEM_MAP.put(1L, new Item(1L, "商品1", "http://图片1", "商品描述1", 1000L));
        ITEM_MAP.put(2L, new Item(2L, "商品2", "http://图片2", "商品描述2", 2000L));
        ITEM_MAP.put(3L, new Item(3L, "商品3", "http://图片3", "商品描述3", 3000L));
        ITEM_MAP.put(4L, new Item(4L, "商品4", "http://图片4", "商品描述4", 4000L));
        ITEM_MAP.put(5L, new Item(5L, "商品5", "http://图片5", "商品描述5", 5000L));
        ITEM_MAP.put(6L, new Item(6L, "商品6", "http://图片6", "商品描述6", 6000L));
        ITEM_MAP.put(7L, new Item(7L, "商品7", "http://图片7", "商品描述7", 7000L));
        ITEM_MAP.put(8L, new Item(8L, "商品8", "http://图片8", "商品描述8", 8000L));
        ITEM_MAP.put(8L, new Item(9L, "商品9", "http://图片9", "商品描述9", 9000L));
        ITEM_MAP.put(8L, new Item(10L, "商品10", "http://图片10", "商品描述10", 10000L));
    }

    /**
     * 模拟实现商品查询
     *
     * @param id
     * @return
     */
    public Item queryItemById(Long id) {
        return ITEM_MAP.get(id);
    }

}

5.1.5.编写ItemController

package com.zpc.item.controller;

import com.zpc.item.entity.Item;
import com.zpc.item.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ItemController {

    @Autowired
    private ItemService itemService;

    /**
     * 对外提供接口服务,查询商品信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "item/{id}")
    public Item queryItemById(@PathVariable("id") Long id) {
        return this.itemService.queryItemById(id);
    }

}

@RestController注解的说明:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

   /**
    * The value may indicate a suggestion for a logical component name,
    * to be turned into a Spring bean in case of an autodetected component.
    * @return the suggested component name, if any (or empty String otherwise)
    * @since 4.0.1
    */
   @AliasFor(annotation = Controller.class)
   String value() default "";

}

从源码可以看出,这是一个组合注解,组合了@Controller和@Response注解。相当于我们同时写了这2个注解。
@GetMapping注解是@RequestMapping(method = RequestMethod.GET)简写方式。其功能都是一样的。

同理还有其它注解:@PostMapping @PutMapping @ResttMapping等
5.1.6.编写程序入口

package com.zpc.item.runner;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author Evan
 */

@SpringBootApplication//申明这是一个Spring Boot项目
@ComponentScan(basePackages = {"com.zpc.item.controller","com.zpc.item.service"})//手动指定bean组件扫描范围
public class ItemApp {
    public static void main(String[] args) {
        SpringApplication.run(ItemApp.class, args);
    }
}

5.1.7.创建application.yml配置文件
Spring Boot以及Spring Cloud项目支持yml和properties格式的配置文件。

yml格式是YAML(Yet Another Markup Language)编写的格式,YAML和properties格式的文件是可以相互转化的。如:

server:
  port: 8081 #服务端口

等价于properties文件的配置:
server.port=8081

配置文件的示例:

server:
  port: 8081 #服务端口

5.1.8.启动程序测试
在这里插入图片描述
5.2.实现订单微服务
5.2.1.创建工程
地址git:
5.2.2.导入依赖

<?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.zpc.microservice</groupId>
    <artifactId>microservice-item</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- 资源文件拷贝插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    </project>

5.2.3.创建订单Order实体

package com.zpc.order.entity;

import java.util.Date;
import java.util.List;

public class Order {

    private String orderId;

    private Long userId;

    private Date createDate;

    private Date updateDate;

    private List<OrderDetail> orderDetails;

    public Order() {

    }

    public Order(String orderId, Long userId, Date createDate, Date updateDate) {
        this.orderId = orderId;
        this.userId = userId;
        this.createDate = createDate;
        this.updateDate = updateDate;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }


    public List<OrderDetail> getOrderDetails() {
        return orderDetails;
    }

    public void setOrderDetails(List<OrderDetail> orderDetails) {
        this.orderDetails = orderDetails;
    }

    @Override
    public String toString() {
        return "Order [orderId=" + orderId + ", userId=" + userId
                + ", createDate=" + createDate + ", updateDate=" + updateDate
                + "]";
    }}

5.2.4.创建订单详情OrderDetail实体
订单与订单详情是一对多的关系。

package com.zpc.order.entity;

public class OrderDetail {

    private String orderId;

    private Item item = new Item();

    public OrderDetail() {

    }

    public OrderDetail(String orderId, Item item) {
        this.orderId = orderId;
        this.item = item;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }

    @Override
    public String toString() {
        return "OrderDetail [orderId=" + orderId + ", item=" + item + "]";
    }

}

5.2.5.将商品微服务项目中的Item类拷贝到当前工程
在这里插入图片描述
5.2.6.编写OrderService
该Service实现的根据订单Id查询订单的服务,为了方便测试,我们将构造数据实现,不采用查询数据库的方式。

package com.zpc.order.service;

import com.zpc.order.entity.Item;
import com.zpc.order.entity.Order;
import com.zpc.order.entity.OrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class OrderService {

    private static final Map<String, Order> ORDER_DATA = new HashMap<String, Order>();

    static {
        // 模拟数据库,构造测试数据
        Order order = new Order();
        order.setOrderId("201810300001");
        order.setCreateDate(new Date());
        order.setUpdateDate(order.getCreateDate());
        order.setUserId(1L);
        List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();

        Item item = new Item();// 此处并没有商品的数据,只是保存了商品ID,需要调用商品微服务获取
        item.setId(1L);
        orderDetails.add(new OrderDetail(order.getOrderId(), item));

        item = new Item(); // 构造第二个商品数据
        item.setId(2L);
        orderDetails.add(new OrderDetail(order.getOrderId(), item));

        order.setOrderDetails(orderDetails);

        ORDER_DATA.put(order.getOrderId(), order);
    }

    @Autowired
    private ItemService itemService;

    /**
     * 根据订单id查询订单数据
     *
     * @param orderId
     * @return
     */
    public Order queryOrderById(String orderId) {
        Order order = ORDER_DATA.get(orderId);
        if (null == order) {
            return null;
        }
        List<OrderDetail> orderDetails = order.getOrderDetails();
        for (OrderDetail orderDetail : orderDetails) {
            // 通过商品微服务查询商品详细数据
            Item item = this.itemService.queryItemById(orderDetail.getItem()
                    .getId());
            if (null == item) {
                continue;
            }
            orderDetail.setItem(item);
        }

        return order;
    }

}

5.2.7.实现ItemService

package com.zpc.order.service;


import com.zpc.order.entity.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ItemService {

    // Spring框架对RESTful方式的http请求做了封装,来简化操作
    @Autowired
    private RestTemplate restTemplate;

    public Item queryItemById(Long id) {
        return this.restTemplate.getForObject("http://127.0.0.1:8081/item/"
                + id, Item.class);
    }

}
5.2.8.编写OrderController
package com.zpc.order.controller;

import com.zpc.order.entity.Order;
import com.zpc.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping(value = "order/{orderId}")
    public Order queryOrderById(@PathVariable("orderId") String orderId) {
        return this.orderService.queryOrderById(orderId);
    }
}

5.2.9.编写程序入口

package com.zpc.order.runner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;

/**
 * @author Evan
 */
@SpringBootApplication//申明这是一个Spring Boot项目
@ComponentScan(basePackages = {"com.zpc.order.controller", "com.zpc.order.service"})//手动指定bean扫描范围
public class OrderApp {
    public static void main(String[] args) {
        SpringApplication.run(OrderApp.class, args);
    }

    /**
     * 向Spring容器中定义RestTemplate对象
     * @return
     */
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

5.2.10.编写application.yml配置文件

server:
  port: 8082 #服务端口

5.2.11.启动测试
在这里插入图片描述
5.3.添加okHttp的支持
okhttp是一个封装URL,比HttpClient更友好易用的工具。看个人习惯,HttpClient用的人也很多。
RestTemplate底层默认使用的jdk的标准实现,如果我们想让RestTemplate的底层使用okhttp,非常简单:
1、添加okhttp依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.0</version>
</dependency>

2、设置requestFactory
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}

在这里插入图片描述
查看 http://localhost:8082/order/201810300001 测试结果是一样的。
5.4.解决订单系统中的url硬编码问题

  1. 通过以上的测试我们发现,在订单系统中要调用商品微服务中的查询接口来获取数据,在订单微服务中将url硬编码到代码中,这样显然不好,因为,运行环境一旦发生变化这个url地址将不可用。
  2. 如何解决呢?
    解决方案:将url地址写入到application.yml配置文件中。

实现:
修改application.yml文件:

server:
  port: 8082 #服务端口
myspcloud:
  item:
    url: http://127.0.0.1:8081/item/

修改ItemService中的实现:

@Service
public class ItemService {

    // Spring框架对RESTful方式的http请求做了封装,来简化操作
    @Autowired
    private RestTemplate restTemplate;

    @Value("${myspcloud.item.url}")
    private String itemUrl;

    public Item queryItemById(Long id) {
        return this.restTemplate.getForObject(itemUrl
                + id, Item.class);
    }

}

5.5.继续优化解决硬编码的问题
在SpringBoot中使用@ConfigurationProperties注解可以非常简单的将配置文件中的值映射成对象。
第一步,创建ItemProperties类:

package com.zpc.order.properties;

public class ItemProperties {
    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

}

第二步,创建OrderProperties类:

package com.zpc.order.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 以myspcloud开头的配置被匹配到
 * @author Evan
 */
@Component
@ConfigurationProperties(prefix="myspcloud")
public class OrderProperties {

    private ItemProperties item = new ItemProperties();

    public ItemProperties getItem() {
        return item;
    }

    public void setItem(ItemProperties item) {
        this.item = item;
    }
}

第三步,在Itemservice中注入该对象:

@Service
public class ItemService {

    // Spring框架对RESTful方式的http请求做了封装,来简化操作
    @Autowired
    private RestTemplate restTemplate;

    //@Value("${myspcloud.item.url}")
    //private String itemUrl;

    @Autowired
    OrderProperties orderProperties;

    public Item queryItemById(Long id) {
        return this.restTemplate.getForObject(orderProperties.getItem().getUrl()
                + id, Item.class);
    }

第四步,启动类中增加bean扫描路径

@ComponentScan(basePackages = {"com.zpc.order.controller","com.zpc.order.service","com.zpc.order.properties"})//
手动指定bean扫描范围

可以看出,这种解决方案比第一种好很多,更加的方便的。
6.Spring Cloud快速入门
6.1.分析硬编码的问题
通过前面5.4、5.5的实现,我们视乎已经解决了url硬编码的问题,但是我们想想:
1、如果商品微服务的ip地址发生了变更,订单微服务中的配置文件也需要跟着修改
2、如果商品微服务有多个,那么在订单微服务中又该如何写地址?

那应该怎么解决呢? – 通过服务注册、发现的机制来完成。

6.2.微服务注册与发现
在这里插入图片描述
由上图可以看出:
1、服务提供者将服务注册到注册中心
2、服务消费者通过注册中心查找服务
3、查找到服务后进行调用(这里就是无需硬编码url的解决方案)
4、服务的消费者与服务注册中心保持心跳连接,一旦服务提供者的地址发生变更时,注册中心会通知服务消费者

6.3.注册中心:Eureka
Spring Cloud提供了多种注册中心的支持,如:Eureka、consul、ZooKeeper等。Eureka已经闭源了。本教程第二篇也会介绍使用其它两种方式作为注册中心。ureka由两个组件组成:Eureka服务器和Eureka客户端。Eureka服务器用作服务注册服务器。Eureka客户端是一个java客户端,用来简化与服务器的交互、作为轮询负载均衡器,并提供服务的故障切换支持。Netflix在其生产环境中使用的是另外的客户端,它提供基于流量、资源利用率以及出错状态的加权负载均衡。
6.3.1.原理
在这里插入图片描述
Eureka包含两个组件:Eureka Server和Eureka Client。
Eureka Server提供服务注册服务,各个节点启动后,会在Eureka Server中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观的看到。
Eureka Client是一个java客户端,用于简化与Eureka Server的交互,客户端同时也就别一个内置的、使用轮询(round-robin)负载算法的负载均衡器。
在应用启动后,将会向Eureka Server发送心跳,默认周期为30秒,如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,Eureka Server将会从服务注册表中把这个服务节点移除(默认90秒)。
Eureka Server之间通过复制的方式完成数据的同步,Eureka还提供了客户端缓存机制,即使所有的Eureka Server都挂掉,客户端依然可以利用缓存中的信息消费其他服务的API。综上,Eureka通过心跳检查、客户端缓存等机制,确保了系统的高可用性、灵活性和可伸缩性。
6.3.2.编写Eureka Server
第一步:创建Maven工程:
git代码地址:
第二步,导入依赖:
这里需要导入Spring Cloud的管理依赖。

<?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.zpc.springcloud.eureka</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>
    <dependencyManagement>
        <dependencies>
            <!-- 导入Spring Cloud的依赖管理 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
    	<!--springboot 整合eureka服务端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

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

第三步,编写程序启动类:

package com.zpc.springcloud.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
 * Eureka注册中心
 */
@SpringBootApplication
@EnableEurekaServer //申明这是一个Eureka服务
public class AppEureka {

   public static void main(String[] args) {
      SpringApplication.run(AppEureka.class, args);
   }
}

第四步,编写application.yml配置文件:

###服务端口号
server:
  port: 8100

###服务名称
spring:
  application:
    name: app-eureka-center

eureka:
  instance:
    #注册中心地址
    hostname: 127.0.0.1
###客户端调用地址
  client:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:8100/eureka/
###是否将自己注册到Eureka服务中,因为该应用本身就是注册中心,不需要再注册自己(集群的时候为true)
    register-with-eureka: false
###是否从Eureka中获取注册信息,因为自己为注册中心,不会在该应用中的检索服务信息
    fetch-registry: false

第五步,启动程序做测试:
在这里插入图片描述
6.4.将商品微服务注册到Eureka
接下来,我们需要将商品的微服务注册到Eureka服务中。

第一步:修改pom文件,引入Spring Cloud的管理依赖以及eureka服务依赖。

<?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.zpc.microservice</groupId>
    <artifactId>microservice-item</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--springboot 整合eureka客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- 资源文件拷贝插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

第二步,修改application.yml配置文件:

###服务端口号(本身是一个web项目)
server:
  port: 8081
###起个名字作为服务名称(该服务注册到eureka注册中心的名称,比如商品服务)
spring:
    application:
        name: app-item
###服务注册到eureka注册中心的地址
eureka:
  client:
    service-url:
           defaultZone: http://127.0.0.1:8100/eureka
###因为该应用为服务提供者,是eureka的一个客户端,需要注册到注册中心
    register-with-eureka: true
###是否需要从eureka上检索服务
    fetch-registry: true

第三步,修改启动类,增加@EnableEurekaClient 注解:

package com.zpc.item.runner;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author Evan
 */
//申明这是一个Spring Boot项目
@SpringBootApplication
@EnableEurekaClient
@ComponentScan(basePackages = {"com.zpc.item.controller","com.zpc.item.service"})
public class ItemApp {
    public static void main(String[] args) {
        SpringApplication.run(ItemApp.class, args);
    }

}

第四步,启动测试:
在这里插入图片描述
至此,我们已经将自己的微服务注册到Eureka server中了。

6.5.订单系统从Eureka中发现商品服务
之前我们在订单系统中是将商品微服务的地址进行了硬编码,现在,由于已经将商品服务注册到Eureka中,所以,只需要从Eureka中发现服务即可。

第一步,在订单系统中添加依赖:

<?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.zpc.microservice</groupId>
    <artifactId>microservice-order</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--springboot 整合eureka客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.9.0</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- 资源文件拷贝插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

第二步,修改application.yml配置文件:

server:
  port: 8082 #服务端口
myspcloud:
  item:
    url: http://127.0.0.1:8081/item/
###起个名字作为服务名称(该服务注册到eureka注册中心的名称,比如订单服务)
spring:
    application:
        name: app-order
###服务注册到eureka注册中心的地址
eureka:
  client:
    service-url:
           defaultZone: http://127.0.0.1:8100/eureka
###因为该应用为服务提供者,是eureka的一个客户端,需要注册到注册中心
    register-with-eureka: true
###是否需要从eureka上检索服务
    fetch-registry: true

第三步,修改ItemService的实现逻辑:

package com.zpc.order.service;
import com.zpc.order.entity.Item;
import com.zpc.order.properties.OrderProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ItemService {

    // Spring框架对RESTful方式的http请求做了封装,来简化操作
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    OrderProperties orderProperties;

    public Item queryItemById(Long id) {

        // 该方法走eureka注册中心调用(去注册中心根据app-item查找服务,这种方式必须先开启负载均衡@LoadBalanced)
        String itemUrl = "http://app-item/item/{id}";
        Item result = restTemplate.getForObject(itemUrl, Item.class, id);
        System.out.println("订单系统调用商品服务,result:" + result);
        return result;
    }
}

第四步,在启动类中添加@EnableEurekaClient注解 ,获取RestTemplate的方法上加 @LoadBalanced注解

package com.zpc.order.runner;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author Evan
 */

@SpringBootApplication//申明这是一个Spring Boot项目
@EnableEurekaClient
@ComponentScan(basePackages = {"com.zpc.order.controller", "com.zpc.order.service","com.zpc.order.properties"})//手动指定bean扫描范围
public class OrderApp {
    public static void main(String[] args) {
        SpringApplication.run(OrderApp.class, args);
    }

    /**
     * 向Spring容器中定义RestTemplate对象
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }

}

第五步,启动测试(此时有3个应用:Eureka注册中心、Item服务、order服务)
在这里插入图片描述
在注册中心http://localhost:8100看到有2个客户端。

微服务从入门到精通【入门篇一】 前言 博主是一名97年的程序员,在职场上摸爬滚打了一年。从毕业至今,生活可以说是五味杂陈。这篇文章是我的第一篇文章,后面会持续更新,希望看完这篇文章的读者能有自己的感悟和收获。本篇文章主要带大家熟悉微服务以及学会应用springcloud的注册中心和负载均衡。 1.了解微服务 1.1什么是微服务? 微服务从字面上解释就是微小的服务,在业界其实并没有给出微服务标准的定义,不过我们可以从俩个维度去理解微服务: . 阅读详情

相关推荐

SpringCloud微服务架构完整教程 - 电商系统实战

SpringCloud电商系统项目概述 业务功能 本项目是一个基于SpringCloud的大型分布式电商系统,主要功能包括: 用户注册、登录、个人信息管理 商品浏览、搜索、详情查看 购物车管理 订单创建、支付、查询 库存管理 支付对接 后台管理 技术特点 采用微服务架构设计 实现分布式事务处理 支持高并发处理方案 完整的服务治理实践 自动化部署能力 技术架构 系统采用多层架构设计: 前端应用层:Web端+移动端+小程序 API网关层:SpringCloud Gateway集群 业务服务层:用户服务、商品服务

weixin_51040479的博客 1275

微服务入门

​ 微服务的架构特征: 微服务的上述特性其实是在给分布式架构制定一个标准,进一步降低服务之间的耦合度,提供服务的独立性和灵活性。做到高内聚,低耦合。 因此,可以认为微服务是一种经过良好架构设计的分布式架构方案 。 但方案该怎么落地?选用什么样的技术栈?全球的互联网公司都在积极尝试自己的微服务落地方案。 其中在Java领域最引人注目的就是SpringCloud提供的方案了。 ​

qq_44732432的博客 2248

Java Microservices 和 Spring Cloud:介绍微服务架构,并使用Spring Cloud来说明其在Java中的实现

介绍 什么是微服务架构 微服务架构的优势和挑战 微服务架构基础 服务分解策略(如何决定服务的边界) 数据管理,如何在分散的服务之间维持数据一致性 服务之间的通信方式 Java Microservices 在Java环境中实现微服务架构的一般步骤 示例:使用Spring Boot创建一个微服务 Spring Cloud介绍 Spring Cloud所提供的功能和组件(如配置管理,服务发现,断路器等) 如何使用Spring Cloud来解决微服务中的某些常见问题 使用Spring Cloud实现微服务

哎 你看的博客 1310

微服务入门:SpringCloud

微服务入门:SpringCloud

qq_59463944的博客 6836

Spring Cloud微服务功能及其组件详细讲解

微服务是一种架构风格,它强调将大型复杂的系统功能根据业务需求切分为一系列小型、独立的服务。每个服务都专注于满足某个具体的业务需求,并且能够独立部署、运行和扩展。这种架构风格使得系统更加灵活、可维护,并且能够更好地应对业务变化和技术挑战。虽然微服务在初始阶段可能会增加开发和维护的难度,因为它要求团队具备更高的分布式系统开发和运维能力。但是,从长远来看,微服务带来的好处是显而易见的。它使得系统更加易于扩展,因为每个服务都可以独立地进行水平扩展,以满足不断增长的业务需求。

Jz_Stu的博客 5562

Spring Cloud(Finchley版本)系列教程(一) 服务注册与发现(eureka)

的构建工具可以使用或,但任然是主流。本文档所使用的开发环境如下:相关模块但主要有5大组件,分别为服务发现组件、、、、。但很多都弃用了,比如Ribbon等。注:版本说明提供了很多服务发现组件,比如:、、等。而是开源的服务发现组件,它包含Server和Client两部分。提供服务发现的能力,每个微服务启动时,都会向注册自己的信息(IP、端口、微服务名称等),存储记录每个微服务的这些信息。是用于简化与交互的Java客户端。微服务启动后,会周期性地(默认30s)向发送心跳以续约自己的可用时间。如果在规定的时间内没有

JingLisen的博客 1897

Spring Cloud系列教程 | 第一篇:微服务架构演进

架构的演变过程: 单体架构——&gt;垂直架构——&gt;soa面向服务架构——&gt;微服务架构 我们为什么要使用Spring Cloud? 单体架构 在网站开发的前期,项目面临的流量相对较少,单一应用可以实现我们所需要的功能,从而减少开发、部署和维护的难度。这种用于简单的增删改查的数据访问框架(ORM)十分的重要。 垂直应用架构 当用户访问量不断的提升,单一应用需要不断的增加服务器来应对...

u011627218的专栏 189

实证研究之|stata清洗charls数据

stata

qq_45313933的博客 6759

spring Boot+spring Cloud实现微服务详细教程第一篇

前些天项目组的大佬跟我聊,说项目组想从之前的架构上剥离出来公用的模块做微服务的开发,恰好去年的5/6月份在上家公司学习了国内开源的dubbo+zookeeper实现的微服务的架构。自己平时对微服务的设计比较上心,第一:是自我感觉做多了垂直应用的项目就觉得味同嚼蜡,所有的模块,技术都冗余的堆积在一个项目里面。耦合度极高。项目的迭代,部署。后期的运营维护都是比较头疼,繁琐的事情。第二:适逢当下应用软件...

weixin_30700099的博客 72

STM32C8T6实战:用PID算法搞定超级电容的10W无线恒功率充电(附代码避坑)

本文详细介绍了如何使用STM32C8T6和PID算法实现超级电容的10W无线恒功率充电。通过优化硬件设计、动态调整PID参数以及三重滤波技术,解决了超级电容充电过程中的功率尖峰和效率问题。附有代码示例和调试经验,帮助开发者快速实现高效稳定的无线充电方案。

weixin_29190169的博客 405

neruolib全脑建模计算框架

neurolib 是一个用python编写的全脑建模计算框架,也是可扩展的、允许轻松实现自定义神经质量模型,能够在介观尺度上表示脑区平均活动。

Rootfyx的博客 1147

Spring Cloud微服务实战教程系列(一)——Spring Cloud微服务简介

        最近在学习Spring Cloud微服务教程,为记录学习中的点点滴滴,也为了给更多的人提供参考,特将学习的过程通过博客连载下来,这是第一篇,讲一下Spring Cloud的技术体系,后面再详细展开。        Spring Cloud是一个基于Spring Boot实现的微服务架构开发工具。它为微服务架构中涉及的配置管理、服务治理、断路器、智能路由、微代理、控制总线、全局锁、决...

u010227646的博客 741

微信小程序 - 解决请求报错 request:fail errcode:-201 cronet_error_code:-201 error_msg:net::ERR_CERT_DATE_INVALID

微信小程序报错“request:fail errcode:-201 cronet_error_code:-201 error_msg:net::ERR_CERT_DATE_INVALID“,微信小程序请求报错,微信小程序errcode:-201,服务器报错,无法调用接口,微信小程序真机https请求失败,微信小程序wx.request接口报错,小程序真机调试运行接口都报错了,真机测试下网络请求都不行了且报错,证书没问题依旧报错,检查HTTPS证书,ssl证书,使用浏览器测试访问证书是正常的,不是证书问题,请

🏆 前端领域优质创作者 1万+

Spring Cloud系列教程 | 第一篇:微服务开篇

目前,Spring Cloud已成为大部分公司的必备课程。即使在项目上未有实践的企业,面试过程中对于微服务的理解和掌握也成为了不可或缺的一个环节。 随着人们生活水平的提高,不同行业的业务也需顺应人们对现代互联网化生活的需求,致使主流技术的快速迭代、变更。应用服务的不断增加,多服务间的相互调用频繁,调用过程就像一个杂乱无章的毛线球,很容易导致牵一发而动全身的情况,经常会由于在服务更新的过程中,没有合理通信,导致数据的丢失。Spring Cloud微服务应运而生,而且Spring Clo...

once先森的博客 186

东方财富个股实时行情爬虫实战:从入门到精通,手把手教你构建股票数据采集系统

在量化投资、股市分析和数据挖掘等领域,获取实时、准确的股票行情数据是第一步也是至关重要的一步。东方财富网作为国内最大的财经门户网站之一,提供了丰富的股票数据和实时行情接口。本文将带你从零开始,构建一个完整的东方财富个股实时行情爬虫系统,涵盖股票代码遍历、JSON接口分析、反爬虫策略应对、数据持久化存储等核心技术点。目录前言一、项目背景与目标1.1 为什么要爬取东方财富数据?1.2 项目目标1.3 技术栈二、接口分析与逆向工程2.1 寻找真实数据接口2.2 简化接口2.3 字段含义对照表三、股票代码获取。

2201_76125261的博客 144

微信8.0所有URL Scheme大全:隐藏入口与使用场景详解 内附195条微信URL Scheme

URL Scheme 类似于一个协议地址,它的作用和网页的https://差不多,只不过它不是打开网页,而是直接跳转到微信App内部的功能页面。→ 打开微信扫一扫→ 打开零钱通详情→ 打开微信面对面支付微信功能的“快捷指令”。整理下来,微信的 URL Scheme 基本覆盖了支付、联系人、扫一扫、小程序、运动设备等多个入口。对开发者来说,这些 Scheme 就像是隐藏的快捷通道,在某些场景(比如支付唤起、活动红包、客服入口)能大大简化流程。微信对外部调用限制非常严格。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 2175

Spring Cloud微服务简介

Spring Cloud微服务 基础知识 微服务构建Spring Boot 服务治理Spring Cloud Eureka 客户端负载均衡Spring Cloud Ribbon 服务容错处理Spring Cloud Hystrix 声明式服务调用Spring Cloud Feign 基础知识 什么是微服务架构? 微服务是系统架构上的一种设计风格; 主旨是将一个原本独立的系统拆分成...

优快云 3万+

C#实战:从零搭建Vosk离线语音转文字系统

本文手把手教你用C#构建离线语音转文字系统,基于NAudio和Vosk实现全流程开发。首先介绍环境搭建,包括NuGet包安装和中文模型配置,强调16kHz单声道音频格式的关键性。接着详细解析音频预处理转换、Vosk模型初始化及识别过程的核心代码,提供多线程优化建议和实时识别扩展思路。文章包含80%以上代码注释,从常见问题排查到性能优化技巧,完整覆盖从"Hello World"到工业级部署的关键技术点,特别适合需要开发本地化语音识别应用的C#开发者。

墨夶的博客 752

Spring Cloud微服务架构

符合"云"理念的大趋势-Spring Clund分布式服务治理的框架

每天都要开心呀(#^.^#) 2万+

qt open3dBPA重建

open3d BPA重建

阁楼 516

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

【亲测免费】 Microservices with Spring Boot and Spring Cloud 2E 教程

Microservices with Spring Boot and Spring Cloud 2E 教程 1、项目介绍 Microservices with Spring Boot and Spring Cloud 2E 是由 Packt Publishing 出版的一本关于使用 Spring Boot 和 Spring Cloud 构建微服务的书籍的代码仓库。该书旨在帮助开发者使用 Sprin...

gitblog_01109的博客 1273

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

使用Spring Cloud搭建微服务项目

使用Spring Cloud搭建微服务项目的案例,使用到Nacos、Dubbo、Sentinel、Seata、gateway等知识。

weixin_70452974的博客 3374

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

在 Solid 中集成 BlockSuite:solid-basic 示例完整解析

本文基于 BlockSuite 仓库中的 [examples/solid-basic](https://link.gitcode.com/i/81787f1fadeb23310019116d2aa68bbc) 示例,讲解如何将 BlockSuite 编辑器与文档集合封装进 Solid 应用中,并完成多文档的创建、切换与展示。读完本文,你将掌握 `pnpm create vite` 脚手架与 Blo

gitblog_00146的博客 1022

【Spring Cloud】初识Spring Cloud

Spring Cloud --- 初识Spring Cloud

2403_87459748的博客 1823

10分钟上手Microservices Event Sourcing:基于Spring Cloud的快速开始教程

想要快速掌握微服务架构中的事件溯源(Event Sourcing)和CQRS模式吗?Microservices Event Sourcing项目为你提供了一个完美的学习平台!这个基于Spring Cloud的在线购物网站项目,不仅展示了微服务的最佳实践,还深入实现了事件溯源和最终一致性,是学习现代分布式系统的绝佳案例。🚀 ## 📋 什么是Microservices Event Sourcin

gitblog_00323的博客 446
上一篇: window 关闭8080端口
下一篇: CentOS 7快速开放端口
满地节操1
博客等级 码龄10年 12粉丝 36原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值