nacos学习笔记(二)

nacos入门案例

一 确认版本

springboot的版本查看地址:https://spring.io/projects/spring-boot#learn

springcloud的版本查看地址:https://spring.io/projects/spring-cloud#overview

详细版本对应信息查看:https://start.spring.io/actuator/info

使用SpringCloud-alibab版本的确定方式:

通过查看springcloud alibaba 官网确定https://github.com/alibaba/spring-cloud-alibaba/wiki/版本说明

最终决定(版本号记忆):

springcloud-alibaba: 2.2.5.RELEASE

springcloud: Hoxton.SR8

springboot: 2.3.2.RELEASE

二 创建父工程

第一步

新建maven项目cloud-demo,因为父工程主要是用来确定版本,所以删掉src目录

第二步

写pom文件

<?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.qf</groupId>
    <artifactId>cloud-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <!--    这是依赖管理,不是依赖,所以右侧maven没有dependency-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.5.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR8</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

创建服务提供者

第一步

新建项目cloud-goods

第二步

修改pom文件

<?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">
    <parent>
        <artifactId>cloud-demo</artifactId>
        <groupId>com.qf</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-goods</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>


    <dependencies>
        <!--        web的场景依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--   端点监控的场景依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--        nacos场景依赖-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

    </dependencies>

</project>

第三步

写配置文件application.yml

spring:
  application:
    name: cloud-goods   #服务名称,必须,唯一
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848  #指定nacos-server的地址
        username: nacos
        password: nacos

server:
  port: 9001   #端口号

第四步

写启动类

添加注解@EnableDiscoveryClient //开关,开启服务的注册与发现功能(springcloud提供的)

package com.qf;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient   //开关,开启服务的注册与发现功能
public class GoodsApp {
    public static void main(String[] args) {
        SpringApplication.run(GoodsApp.class,args);
    }
}



第五步启动

打开nacos查看是否完成注册

创建新模块

第一步

创建项目cloud-entity

第二步

修改pom文件,添加依赖

<?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">
    <parent>
        <artifactId>cloud-demo</artifactId>
        <groupId>com.qf</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-entity</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>


第三步

创建实体类

package com.qf;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Goods {

    private String goodsName;
    private double price;
}



第四步

修改cloud-goods的pom文件,添加依赖

<dependency>
    <groupId>com.qf</groupId>
    <artifactId>cloud-entity</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>


第五步

在cloud-goods中新建controller

package com.qf.controller;

import com.qf.Goods;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("goods")
public class GoodsController {
    
    @RequestMapping("findById/{id}")
    public Goods findById(@PathVariable String id) {
        System.out.println("id" + id);
        return new Goods("小米", 99);
    }


}

创建服务消费者

第一步

创建项目cloud-order

第二步

修改pom文件,复制cloud-goods的即可

<dependencies>
    <!--        web的场景依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--   端点监控的场景依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--        nacos场景依赖-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

    <dependency>
        <groupId>com.qf</groupId>
        <artifactId>cloud-entity</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>

</dependencies>


第三步

写配置文件

spring:
  application:
    name: cloud-order   #服务名称,必须,唯一
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848  #指定nacos-server的地址
        username: nacos
        password: nacos

server:
  port: 9002   #端口号

第四步

启动类

package com.qf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class OrderApp {
    public static void main(String[] args) {
        SpringApplication.run(OrderApp.class, args);
    }
}



第五步启动

查看nacos是否注册成功

实现远程调用

第一步

在order启动类加个类 RestTemplate

package com.qf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class OrderApp {
    public static void main(String[] args) {
        SpringApplication.run(OrderApp.class, args);
    }

    @Bean
    public RestTemplate initRestTemplate(){
        return  new RestTemplate();
    }
}


第二步

在order消费者新建个controller

package com.qf.controller;

import com.qf.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/save")
    public Map save() {
        //远程调用cloud-good服务,获取goods信息,发送http请求(httpclient-java)=> resttemplate-spring提供
        String url = "http://localhost:9001/goods/findById/1";
        Goods goods = restTemplate.getForObject(url, Goods.class);
        System.out.println(goods);
        //2.保存订单
        System.out.println("保存成功");
        return new HashMap() {
            {
                put("code", "200");
                put("msg", "success");
            }
        };

    }
}

第三步启动

启动goods 和order 并且启动nacos

访问http://localhost:9002/order/save ,查看是否访问成功

优化

在OrderController中地址不能写死,应写服务名称

package com.qf.controller;

import com.qf.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/save")
    public Map save() {
        //远程调用cloud-good服务,获取goods信息,发送http请求(httpclient)=> resttemplate
        String serverName ="cloud-goods";
        String url = "http://"+serverName+"/goods/findById/1";
        Goods goods = restTemplate.getForObject(url, Goods.class);
        System.out.println(goods);
        //2.保存订单
        System.out.println("保存成功");
        return new HashMap() {
            {
                put("code", "200");
                put("msg", "success");
            }
        };

    }
}


访问结果报错,因为发送请求需要通过cloud-goods去注册中心拿实例列表,这个事情需要由Ribbon完成,但是Ribbon没生效。需要在order启动类里RestTemplate上加个注解@LoadBalanced,springcloud提供的一个注解。

end
  • 作者:(联系作者)
  • 更新时间:2022-07-29 14:33
  • 版权声明:自由转载-非商用
  • 转载声明:如果是转载栈主转载的文章,请附上原文链接