Eureka基本使用 結合feign

eureka Server 服務註冊與發現服務器代碼 spring boot 2.0.4

1、pom  springBoot 2.0.4,同樣屬於springBoot-web  spring-cloud...

...
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
... 
          <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
           </dependency>

2、單節點服務註冊中心 yml 配置

server:
  port: 8769
eureka:
  instance:
    hostName: localhost
  client:
    registerWithEureka: false #默認true,不許要註冊自己
    fetchRegistry: false #單節點,不需要同步其他註冊中心
    service-url:
      defaultZone:  http://${eureka.instance.hostName}:${server.port}/eureka/

3、啓動代碼

package com.gy.sc.discoveryeureka;

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

@SpringBootApplication
@EnableEurekaServer // 開啓註冊中心server
public class DiscoveryEurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(DiscoveryEurekaApplication.class, args);
    }
}

4、驗證server啓動結果

服務提供者代碼

1、pom依賴 sb版本統一2.0.4 web項目 spring-cloud...



        <dependency>
            <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
// mysql數據看訪問依賴、jpa...

2、yml配置 注意:eureka配置跟spring相關配置同級!

server:
  port: 8899
spring:
  application:
    name: sc-provider-user # 應用服務名稱
  datasource:
    username: root
    password: FFhcc01180325
    url: jdbc:mysql://127.0.0.1:3306/wisdom
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        enable_lazy_load_no_trans: true
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8769/eureka/
  instance:
    prefer-ip-address: true
    lease-renewal-interval-in-seconds: 10
  register-with-eureka: true

3、服務暴露

package com.gy.sc.scprovideruser.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.gy.sc.scprovideruser.entity.TUser;
import com.gy.sc.scprovideruser.repository.TUserRepository;

@RestController
public class TUserController {

    @Autowired
    private TUserRepository tUserRepository;

    /**
     * @author GY
     * @date 2018年10月29日
     * @說明:getOne是返回一個實體的引用——代理對象,findOne是返回實體
     * Jpa自動適配了數據庫表跟實體的駝峯映射
     */
    @GetMapping("/get/user/{id}")
    public TUser getUserById(@PathVariable("id") Integer id) {
        // 使用findOne不會報錯,使用getOne 如果TUser類上不加 @JsonIgnoreProperties... 就會報錯
        // 見:https://blog.csdn.net/gw816/article/details/80401284#commentBox
        Example<TUser> example = Example.of(new TUser().setId(id));
        Optional<TUser> findOne = tUserRepository.findOne(example);
        if(findOne.isPresent())
            return findOne.get();
        return null;
    }

    @GetMapping("/add/user")
    public TUser addUser(TUser tUser) {
        TUser user = tUserRepository.save(tUser);
        return user;
    }

}

entity...repository...

4、啓動類

package com.gy.sc.scprovideruser;

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

@EnableDiscoveryClient
@SpringBootApplication
public class ScProviderUserApplication {

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

服務調用者代碼(可能成爲提供者,也需要註冊自己的服務)

RestTemplate使用

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

調用

@Autowired
    private RestTemplate restTemplate;

    @GetMapping("movie/get/user2/{id}")
    public TUser findAUserById2(@PathVariable("id") Integer id)  {
        // 服務名稱必須用大寫!!!
        TUser tUser2 = restTemplate.getForObject(
                "http://SC-PROVIDER-USER/get/user/" + id,  TUser.class);
        System.out.println(tUser2);
        return tUser2;
    }

結果

feign使用

1、pom依賴,整合feign

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
           </dependency>
        <!--  https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-feign -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-feign</artifactId>
                <version>1.4.4.RELEASE</version>
            </dependency>

2、yml配置

server:
  port: 8800
spring:
  application:
    name: sc-consumer-movie
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8769/eureka/
  instance:
    prefer-ip-address: true
    lease-renewal-interval-in-seconds: 10
  register-with-eureka: true

3、remote(應該可以跟服務提供者使用公共controller jar包接口)

package com.gy.sc.scconsumermovie.remote;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gy.sc.scconsumermovie.entity.TUser;

@FeignClient(name = "sc-provider-user")
public interface UserRemote {

    @RequestMapping("/get/user/{id}")
    public TUser getUserById(@PathVariable("id") Integer id);

}

entity...(跟服務提供者可以共用jar包)

4、啓動類

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

5、調用註冊服務(應該是service層調用)

    @Autowired
    private UserRemote userRemote;

    @GetMapping("movie/get/user/{id}")
    public TUser findAUserById(@PathVariable("id") Integer id) {
        TUser tUser = userRemote.getUserById(1);
        System.out.println(tUser);
        return tUser;
    }

調用結果

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章