springcloud 微服务搭建

前段时间试着搭建一个springcloud微服务demo,还是记录一下!
在这里插入图片描述ep-api主要定义接口、实体model,以及工具等。
eureka注册服务中心application.yml配置,以及注册用户登录安全认证:
在这里插入图片描述

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 新版本的security默认开启csrf,不关闭的话,服务是注册不上的
        http.csrf().disable(); //关闭csrf
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); //开启认证
    }
}
server:
  port: 8072

#设置该服务注册中心的hostname
eureka:
  instance:
    hostname: eureka8072
  #目前创建的应用是一个服务注册中心,而不是普通的应用,默认情况下,这个应用会想注册中心(也就是自己)注册自己,
  client:
    #设置为false表示禁止这种自己向自己注册的默认行为
    register-with-eureka: false
    #表示不去检索其他的服务,因为服务注册中心本身的职责就是维护服务实例,它不需要去检索其他服务
    fetch-registry: false
    #指定服务注册中心的位置
    service-url:
      defaultZone: http://admin:admin123@eureka8071:8071/eureka,http://admin:admin123@eureka8070:8070/eureka
  server:
    #测试时关闭自我保护机制,保证不可用服务及时被踢出
    enable-self-preservation: false
    eviction-interval-timer-in-ms: 4000

# 安全认证的配置,不加安全认证的话服务注册就不需要加用户和密码
spring:
  security:
    user:
      name: admin   #用户名
      password: admin123  #密码
#日志输出
logging:
  file:
    name: logs/eureka8072.log
    #日志文件大小
    max-size: 10MB
    #日志保留天数
    max-history: 14

ep-provider-user 服务提供者模块:
在这里插入图片描述application.yml配置文件:

server:
  port: 8080
#配置服务名称
spring:
  application:
    name: ep-provider-user
  #数据库连接配置
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/tms?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
  #redis数据库连接
  redis:
    host: 192.168.2.123
    port: 6380
    password: ""
    database: 0

#eureka 的连接地址
eureka:
  client:
    service-url:
      defaultZone: http://admin:admin123@eureka8070:8070/eureka,http://admin:admin123@eureka8071:8071/eureka,http://admin:admin123@eureka8072:8072/eureka
  instance:
    hostname: 192.168.2.123
    #实例配置,同名的服务,注册只能有一个实例
    instance-id: ${eureka.instance.hostname}:${server.port}:${spring.application.instance_id:${random.value}}
    appname: ${spring.application.name}

    #每间隔2s,向服务端发送一次心跳,证明自己在线
    lease-renewal-interval-in-seconds: 2
    #告诉服务端,在10s没没有发送心跳的,表示出现故障了,可以将我踢出掉
    lease-expiration-duration-in-seconds: 10
    #访问路径可以显示IP地址,默认是false
    prefer-ip-address: true

#扫描mapper.xml文件
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
#控制台输出数据库执行操作sql语句
logging:
  level:
    com:
      ep:
        mapper: debug
  #日志输出到文件中
  file:
    name: logs/ep-provider-user.log
    #日志保留天数
    max-history: 14
    #日志文件大小
    max-size: 10MB

ep-feign-user实现负载均衡模块:
在这里插入图片描述UserFeignService接口定义

@FeignClient(name = "ep-provider-user",fallbackFactory = UserFallbackFactory.class)
public interface UserFeignService {
    @RequestMapping(value = "/user/addUser",method = RequestMethod.POST,consumes = "application/json")
    public String addUser(@RequestParam("userName") String name, @RequestBody UserEntity userEntity);
    @RequestMapping(value = "/user/userAllList",method = RequestMethod.GET,consumes = "application/json")
    public String queryAllList();
    @RequestMapping(value = "/user/userList",method = RequestMethod.GET,consumes = "application/json")
    public String queryList(@RequestParam Map<String, Object> map);
    @RequestMapping(value = "/user/loginCheck",method = RequestMethod.POST,consumes = "application/json")
    public String loginCheck(@RequestParam("userName") String userName, @RequestParam("password") String password);
    @RequestMapping(value = "/menu/menuList",method = RequestMethod.GET,consumes = "application/json")
    public String menuList();
    @RequestMapping(value = "/user/userTest",method = RequestMethod.GET,consumes = "application/json")
    public String userTest();
}

UserFallbackFactory异常处理

package com.ep.fallback;

import com.ep.model.UserEntity;
import com.ep.service.UserFeignService;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Component
public class UserFallbackFactory implements FallbackFactory<UserFeignService> {
    @Override
    public UserFeignService create(Throwable throwable) {
        return new UserFeignService(){
            @Override
            public String addUser(@RequestParam("userName") String name,@RequestBody UserEntity userEntity) {
                return throwable.getMessage();
            }

            @Override
            public String queryAllList() {
                return throwable.getMessage();
            }

            @Override
            public String queryList(@RequestParam Map<String, Object> map) {
                return throwable.getMessage();
            }

            @Override
            public String loginCheck(@RequestParam("userName") String userName, @RequestParam("password") String password) {
                return throwable.getMessage();
            }

            @Override
            public String menuList() {
                return throwable.getMessage();
            }

            @Override
            public String userTest() {
                return throwable.getMessage();
            }
        };
    }
}

ep-api-gateway网关模块
在这里插入图片描述

application.yml配置文件

server:
  port: 9000
#配置服务名称
spring:
  application:
    name: ep-api-gateway
  #redis数据库连接
  redis:
    host: 192.168.2.123
    port: 6380
    password: ""
    database: 0
    timeout: 6000ms # 连接超时时长(毫秒)
    jedis:
      pool:
        max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1ms  # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 10 # 连接池中的最大空闲连接
        min-idle: 5 # 连接池中的最小空闲连接
  #处理中文乱码
  http:
    encoding:
      charset: utf-8
      enabled: true
      force: true

#配置路由规则
zuul:
  routes:
    ep-feign-user: /u/**
  #忽略掉某一些接口路径
  #ignored-patterns: /**/hello/**
  #配置网关路由前缀
  prefix: /ep
  #禁用zuul默认的错误过滤器,使用自定义错误过滤器
  SendErrorFilter:
    error:
      disable: true
  sensitive-headers:   #不过滤客户端的任何请求头(如:Cookie不会被过滤)
  #  ignored-headers:   #微服务之间的传递不过滤任何请求头(如:微服务之间传递Cookie不会被过滤)

#配置API网关到注册中心上,API网关也将作为一个服务注册到eureka-server上
eureka:
  client:
    service-url:
      defaultZone: http://admin:admin123@eureka8070:8070/eureka,http://admin:admin123@eureka8071:8071/eureka,http://admin:admin123@eureka8072:8072/eureka

#日志输出
logging:
  file:
    name: logs/ep-api-gateway.log
    #日志文件大小
    max-size: 10MB
    #日志保留天数
    max-history: 14

解决客户端与服务端的跨域访问问题 WebMvcConfig

/**
 * @author 作者: wdr
 * @version 创建时间:2020/4/30 16:34
 * 类说明  配置解决客户端与服务端的跨域访问问题
 */
@Configuration
public class WebMvcConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowCredentials(true)
                        .maxAge(3600)
                        .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials","Access-Control-Allow-Headers","token")
                        .allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE");
            }
        };
    }
}

大体上完成微服务搭建,访问流程

ep-api-gateway --> ep-feign-user --> ep-provider-user
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值