栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springcloud项目小小实战

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springcloud项目小小实战

一、新建父项目,再加modul

父项目pom.xml


    
    
         org.springframework.boot
        spring-boot-starter-parent
        2.2.5.RELEASE
    

    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Hoxton.SR3
                pom
                import
            
        
    

    
    
        
            junit
            junit
            4.12
            test
        
        
            org.projectlombok
            lombok
        
    
    
        springcloud-eureka-server
        springcloud-order-server
        springcloud-user-server
        springcloud-user-common
        springcloud-pay-server
        springcloud-zuul-server
    

 二、eureka

1.pom.xml导入依赖


        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        

2.在resources下建application.yml

server: # Eureka服务端端口号
  port: 1010

eureka: # Eureka配置
  instance: # 定义该服务Ip
    hostname: localhost
    # 从上一次收到心跳之后,等待下一次心跳的时间,也就是服务剔除时间,默认90秒
    lease-expiration-duration-in-seconds: 30
    # 发送心跳时间,默认30秒
    lease-renewal-interval-in-seconds: 10
  client: # Eureka客户端配置
    registerWithEureka: false # 该服务不注册到到注册中心
    fetchRegistry: false # 该服务不拉取注册表
    serviceUrl: # 注册中心地址 http://localhost:1001/eureka/
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  server:
    enable-self-preservation: false # 关闭Eureka自我保护机制
      # 自我保护续约百分比,默认是0.85
    renewal-percent-threshold: 0.85

3.在src/main/java下建cn.zyb.EurekaServerApp

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApp {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApp.class, args);
    }
}
三、order

1.pom.xml导入依赖


        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            cn.zyb
            springcloud-user-common
            1.0-SNAPSHOT
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-ribbon
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-hystrix
        


    

2.在resources下建application.yml

server:
  port: 1030 # user服务端口号

eureka:
  client: # Eureka客户端配置,指向注册中心地址
    serviceUrl:
      defaultZone: http://localhost:1010/eureka/
  instance:
    prefer-ip-address: true # 开启使用IP地址进行注册
    instance-id: order-server:1030 # 修改实例Id
spring:
  application: # 指定此服务的应用名称
    name: order-server
ribbon:
  ReadTimeout: 3000					#读取超时时间
  ConnectTimeout: 3000				#链接超时时间
  MaxAutoRetries: 1 				#重试机制:同一台实例最大重试次数
  MaxAutoRetriesNextServer: 1 		#重试负载均衡其他的实例最大重试次数
  OkToRetryOnAllOperations: false  	#是否所有操作都重试,因为针对post请求如果没做幂等处理可能会造成数据多次添加/修改
  eager-load:
    enabled: true #开启饥饿加载
    clients: user-server #针对于哪些服务需要饥饿加载

hystrix:
  command:
    default:
      circuitBreaker:
        requestVolumeThreshold: 10 #20个请求中
        errorThresholdPercentage: 50 #出错百分比阈值
        sleepWindowInMilliseconds: 50000 #短路5秒钟,尝试恢复
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 9000 #调用者执行的超时时间,超时触发熔断,这个值默认的不合理,需要计算

3.在src/main/java下建cn.zyb.OrderServerApp

@SpringBootApplication
// 表名此服务是Eure客户端,开启Eureka客户端功能,不加此注解默认也开启客户端功能
@EnableEurekaClient
// 开启熔断功能
@EnableCircuitBreaker
public class OrderServerApp {

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

    @Bean
    @LoadBalanced // 让RestTemplate拥有负载均衡能力
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Bean
    public RandomRule randomRule(){
        return new RandomRule();
    }

}

4.src/main/java下建cn.zyb.controller.OrderController

@RestController
@DefaultProperties(defaultFallback = "fallbackMethod")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getById/{id}")
    @HystrixCommand // 标记方法熔断,fallbackMethod指定的是托底方法名称,当远程服务调用出现异常,或是方法本身出现异常,会触发托底方法
    public User getUserById(@PathVariable("id") Long id){
        // 1.定义要请求的路径,后续不会如此使用
        String url = "http://user-server/getById/"+id;
        // 2.使用RestTemplate工具类发送Http请求调用User接口
        return restTemplate.getForObject(url, User.class);
    }

    // 方法独立托底方法
    
    

    // 接口类统一托底方法,不管是统一还是接口局部托底返回值类型都需要一致
    public Object fallbackMethod(){
        return new User(-1L, "触发熔断", "熔断触发了!!!");
    }

 四、pay

1.pom.xml导入依赖


        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            cn.zyb
            springcloud-user-common
            1.0-SNAPSHOT
        

        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
    

2.在resources下建application.yml

server:
  port: 1040 # user服务端口号

eureka:
  client:
    serviceUrl: # Eureka客户端配置,指向注册中心地址
      defaultZone: http://localhost:1010/eureka/
  instance:
    prefer-ip-address: true # 开启使用IP地址进行注册
    instance-id: pay-server # 修改实例Id
spring:
  application:
    name: payr-server
logging:
  level:
    cn.zyb: debug # 指定为debug你才看的到feign的日志
feign:
  hystrix:
    enabled: true #开启熔断支持

3.在src/main/java下建cn.zyb.PayServerApp

@SpringBootApplication
@EnableEurekaClient // 表示Eureka客户端
@EnableFeignClients // 开启OpenFeign支持
public class PayServerApp {

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

}

4.src/main/java下建cn.zyb.controller.OrderController,cn.zyb.config.FeignConfiguration,cn.zyb.feignClient下建两个UserFeignClient,UserFeignClientFallbackFactory

@Configuration
public class FeignConfiguration {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;	//打印Feign的所有日志
    }
}
@RestController
public class PayController {

    // 注入feign接口
    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/getById/{id}")
    public User getById(@PathVariable("id") Long id){
        // 调用OpenFeign接口,通信User服务
        return userFeignClient.getById(id);
    }
}
// 指定要调用的服务的应用名称 , fallbackFactory指定托底工厂类
@FeignClient(value = "user-server", fallbackFactory = UserFeignClientFallbackFactory.class)
public interface UserFeignClient {

    // openFeign接口编写,就是直接复制目标服务的请求接口方法
    // 调用哪个接口,就拷贝哪个接口方法
    
    @GetMapping("/getById/{id}")
    User getById(@PathVariable("id") Long id);

}
@Component // 必须交给spring管理
public class UserFeignClientFallbackFactory implements FallbackFactory {

    
    @Override
    public UserFeignClient create(Throwable throwable) {
        return new UserFeignClient() {
            @Override
            public User getById(Long id) {
                return new User(-1L, "触发熔断", "服务不可以,请稍后重试!");
            }
        };
    }

}

五、user-common

在src/main/java下建cn.zyb.domain.User

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private String desc;
}

 六、user

1.pom.xml导入依赖


        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            cn.zyb
            springcloud-user-common
            1.0-SNAPSHOT
        
    

2.在resources下建application.yml

server:
  port: 1020 # user服务端口号

eureka:
  client:
    serviceUrl: # Eureka客户端配置,指向注册中心地址
      defaultZone: http://localhost:1010/eureka/
  instance:
    prefer-ip-address: true # 开启使用IP地址进行注册
    instance-id: user-server-1020 # 修改实例Id
spring:
  application:
    name: user-server
feign:
  hystrix:
    enabled: true #开启熔断支持
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000   #hystrix超时时间

3.在src/main/java下建cn.zyb.UserServerApp

@SpringBootApplication
// 表名此服务是Eure客户端,开启Eureka客户端功能,不加此注解默认也开启客户端功能
@EnableEurekaClient
public class UserServerApp {

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

}

4.src/main/java下建cn.zyb.controller.UserController

@RestController
public class UserController {

    @Value("${server.port}")
    private String port;

    @GetMapping("getById/{id}")
    public User getById(@PathVariable("id") Long id) {
        return new User(id, "源码时代", "我在源码时代学java port=" + port);
    }

}

 七、zuul

1.pom.xml导入依赖


        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-zuul
        
    

2.在resources下建application.yml

# 指定user服务端口
server:
  port: 1050

eureka:
  client:
    serviceUrl: # 指定eureka注册中心地址,就是我们自己的eureka的访问地址
      defaultZone: http://localhost:1010/eureka/
  instance: # 开启根据IP进行注册
    prefer-ip-address: true
    instance-id: zuul-server # 指定实例Id

spring:
  application: # 指定user服务的名称,也叫应用名称,集群的应用名称必须是同一个
    name: zuul-server

zuul:
  prefix: "/apis"  #统一访问前缀
  ignoredServices: "*"  #禁用掉使用浏览器通过服务名的方式访问服务
  routes:
    pay-server: "/pay/**"   #指定pay-server这个服务使用 /pay路径来访问  - 别名
    order-server: "/order/**"   #指定order-server这个服务使用 /order路径来访问

3.在src/main/java下建cn.zyb.ZuulServerApp

@SpringBootApplication
// 开启Eureka客户端服务,也可以不加,只要导入了Jar包默认就开启客户端
@EnableEurekaClient
// 开启Zuul服务
@EnableZuulProxy
public class ZuulServerApp {

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

}
 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1036468.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号