springcloud微服务架构搭建入门笔记

  • 注册管理服务器

    •   应用入口配置
1 @SpringBootApplication
2 @EnableEurekaServer
3 public class GatewayApplication {
4     public static void main(String[] args) {
5         SpringApplication.run(GatewayApplication.class, args);
6     }
7 }
View Code
    • yml配置

 

 1 spring:
 2   application:
 3     name: gateway    #服务名称
 4 
 5 server:
 6   port: 8801    #端口
 7 
 8 eureka:
 9   instance:    
10     hostname: localhost    
11   client:
12     registerWithEureka: false
13     fetchRegistry: false
14     serviceUrl:
15       defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
View Code
  • 业务服务器

    •   yml配置
 1 server:
 2   port: 8804
 3 
 4 spring:
 5   application:
 6     name: client-feign
 7 
 8 eureka:
 9   client:
10     service-url:
11       defaultZone:  http://localhost:8801/eureka/
View Code

 

    • 应用入口

 

 1 @SpringBootApplication
 2 @EnableEurekaClient    启动EurekaServer,用于将本服务注册到注册器上
 3 @EnableFeignClients    开启Feign客户端,用于访问注册器上的其他服务
 4 public class ClientFeignApplication {
 5 
 6     public static void main(String[] args) {
 7         SpringApplication.run(ClientFeignApplication.class, args);
 8     }
 9 
10 }
View Code
    • 外部服务请求客户端
 1 import org.springframework.cloud.openfeign.FeignClient;
 2 import org.springframework.web.bind.annotation.RequestMapping;
 3 import org.springframework.web.bind.annotation.RequestParam;
 4 import org.springframework.web.bind.annotation.ResponseBody;
 5 
 6 @FeignClient("service")    #注册器中注册过的服务名,即其他服务yml中配置的spring.application.name
 7 public interface ClientForRibbon {
 8     @RequestMapping("/login")    #外部服务请求路径
 9     @ResponseBody
10     String login(@RequestParam("name")String name, @RequestParam("passwd")String passwd);    #参数前需用注解注明参数名称
11 }
View Code
    • 控制层
 1 import com.example.clientfeign.feign.ClientForRibbon;
 2 import org.springframework.beans.factory.annotation.Autowired;
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 
 7 @RestController
 8 public class LoginController {
 9 
10     @Autowired
11     //注入其他服务客户端
12     private ClientForRibbon server;
13 
14     @RequestMapping("/loginOut")
15     public String loginOut(String name,String passwd){
16         //利用客户端调用其他服务
17         return server.login(name,passwd);
18     }
19 }
View Code

 

demo: https://github.com/malefeng/springcloudDemo.git

 

你可能感兴趣的:(springcloud微服务架构搭建入门笔记)