码迷,mamicode.com
首页 > 编程语言 > 详细

springCloud微服务入门

时间:2018-11-24 20:56:11      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:disco   group   目录   enabled   interface   toc   inter   服务框架   hostname   

目录

前言

springCloud是一个微服务框架集。
eureka来实现zookeeper;

Eureka

注册中心server

新建

选择版本: 1.5.17
cloud dicovery ---  eureka server

配置

  • 启动类
# 启动类添加注解:
@EnableEurekaServer
  • 简单配置
# application.yml
server:
  port: 8761
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/

查看127.0.0.1:8761/

  • 集群配置
# application.yml
spring:
  application:
    name: server中心
  profiles:
    active: server1

# application-server1.yml
server:
  port: 8761
eureka:
  instance:
    hostname: server1
  client:
    service-url:
      defaultZone: http://127.0.0.1:8762/eureka/ # 后面可以添加更多地址,用逗号分隔

# application-server2.yml
server:
  port: 8762
eureka:
  instance:
    hostname: server2
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/

启动参数

--spring.profiles.active=prod

服务提供者service

新建

和注册中心一样

配置

  • 启动类
和注册中心一样
  • 简单配置
spring:
  application:
    name: service01
server:
  port: 8081

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

服务消费者controller

新建

和之前一样

配置

  • 启动类
# 添加注解
@EnableDiscoveryClient

# 添加属性
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
    return new RestTemplate();
}
  • 配置
spring:
  application:
    name: controller01
server:
  port: 8764
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/ 

使用

@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("test")
    public String test() {
        String forObject = restTemplate.getForObject("http://service01/test", String.class);
        return forObject;
    }
}

Feign负载均衡

  • 引用
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
  • 启动类
@EnableFeignClients
@EnableDiscoveryClient
  • service层接口
@FeignClient(value = "springcloud-server")
public interface TestService {
 
   @RequestMapping("/test")
   public String test();
 
}
  • controller调用
@RestController
public class TestController {
 
   @Autowired
   private  TestService testService;
 
   @RequestMapping(value = "/test",method = RequestMethod.GET)
   public String test(){
      return  testService.test();
   }
}

springCloud微服务入门

标签:disco   group   目录   enabled   interface   toc   inter   服务框架   hostname   

原文地址:https://www.cnblogs.com/birdofparadise/p/10013165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!