springcloud(7)-配置客户端

1.在视图微服务product-view的pom.xml中增加

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

2.bootstrap.yml,其中main表示所在分支

spring:
  cloud:
    config:
      label: main
      profile: dev
      discovery:
        enabled:  true
        serviceId:  config-server
  client:
    serviceUrl:
      defaultZone:  http://localhost:8761/eureka/

3.appllication.yml

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
spring:
  application:
    name: product-view-service-feign
  zipkin:
    base-url: http://localhost:9411
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
    suffix: .html
    encoding: UTF-8
    servlet:
      content-type: text/html
    mode: HTML5

4.ProductController

@Controller
@RefreshScope
public class ProductController {

    @Autowired
    ProductService productService;

    @Value("${version}")
    String version;

    @RequestMapping("/products")
    public Object products(Model m) {
        List<Product> ps = productService.listProducts();
        m.addAttribute("version",version);
        m.addAttribute("ps", ps);
        return "products";
    }
}

5.products

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>products</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <style>

        table {
            border-collapse:collapse;
            400px;
            margin:20px auto;
        }
        td,th{
            border:1px solid gray;
        }

    </style>
</head>
<body>

<div class="workingArea">
    <table>
        <thead>
        <tr>
            <th>id</th>
            <th>产品名称</th>
            <th>价格</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="p: ${ps}">
            <td th:text="${p.id}"></td>
            <td th:text="${p.name}"></td>
            <td th:text="${p.price}"></td>
        </tr>
        </tbody>
        <tr>
            <td align="center" colspan="3">
                <p th:text="${version}" >zhangdemo springcloud version unknown</p>
            </td>
        </tr>
    </table>
</div>

</body>

</html>

6测试http://localhost:8012/products

image-20201116111553178

ps.显示两条报错信息

(1.org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'eurekaAutoServiceRegistration': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)

(2 java.lang.IllegalArgumentException: Could not resolve placeholder 'version' in value "${version}"

原因:需要将label中的master改为main,git分支在2020.10.01之后分支就默认为main

原文地址:https://www.cnblogs.com/NaoDaiYouDianDa/p/13985386.html