Spring 微服务搭建

1.侦听服务注册(简称服务端)

第一步:创建springboot 项目引入Cloud Disocovery的Eureka Server

第二步:启动类添加@EnableEurekaServer 注解标记EurekaServer服务

第三步:配置项目文件官方推荐 

  eureka.client.register-with-eureka=false
  eureka.client.fetch-registry=false
  #这两个配置禁止此服务作为服务注册到服务中心

  eureka.instance.hostname=localhost
  #这个当前主机地址 不填本机的话 服务中心可能会被当作一个服务去注册
  eureka.client.service-url.defaultZone=http://${server.address}:${server.port}/eureka/
  #eureka服务地址
 
  eureka.dashboard.enabled=true
  #是否启用Eureka的仪表板。默认为true.
  eureka.dashboard.path=/eurekas
  #到Eureka仪表板的服务路径(相对于servlet路径)。默认为“/” 不能同服务中心地址一样eureka

  eureka.server.eviction-interval-timer-in-ms=15000
  #开启清除无效服务的定时任务,时间间隔。默认1分钟
   
  eureka.server.sync-when-timestamp-differs=true
  #当时间戳不一致的时候,是否进行同步


2.子服务注册(简称客户端)

 

第一步:创建springboot 项目引入Cloud Disocovery的Eureka Client

    以及引入spring-boot-starter-actuator 健康检查

第二步:启动类添加@EnableEurekaClient注解标记EurekaClient

    或者@EnableDiscoveryClient

第三步:配置项目文件    

  spring.application.name=testClient1
  #testClient 在服务中心显示的服务名(应用名)  
  eureka.client.service-url.defaultZone=http://${server.address}:8882/eureka/  
  #配置注册到具体哪个服务中心
  eureka.client.healthcheck.enabled=true
  #监控健康状态
  management.endpoint.health.show-details=ALWAYS
  #需要监测的内容等级

  management.endpoints.web.exposure.include=*
  #需要监测的等级内的哪些部分信息
  eureka.instance.prefer-ip-address=true
  #允许使用ip注册服务id
  eureka.instance.instance-id=127.0.0.1
  #此服务id
  spring.cloud.inetutils.preferred-networks=127.0.0.1
  #注册时首选网关

3.服务状态监控插件spring-boot-admin

第一步:服务端添加以下jar包

  <groupId>de.codecentric</groupId>
  <artifactId>spring-boot-admin-server-ui</artifactId>
  <groupId>de.codecentric</groupId>
  <artifactId>spring-boot-admin-starter-server</artifactId>

第二步:服务端配置监控页面

  spring.boot.admin.context-path=/admin
  #服务监控地址

  spring.boot.admin.ui.title=XXXXXX
  spring.boot.admin.ui.brand=<img src="assets/img/icon-spring-boot-admin.svg"><span>XXXXXXxX</span>
  #监控标题

第三步:服务端启动类添加@EnableAdminServer 

第四步:客户端的启动类上的@EnableEurekaClient注解改为@EnableDiscoveryClient

第五步:客户端配置

  spring.boot.admin.client.instance.service-base-url=http://${server.address}:0000/admin/
  #服务端地址 注册服务地址
  spring.boot.admin.client.enabled=true
  #启用此客户端
  spring.boot.admin.client.url=http://127.0.0.1:8082/admin
  #该客户端地址
  
  spring.boot.admin.client.instance.prefer-ip=true
  #允许使用IP作为主机名注册
  logging.file.name=/var/log/sample-boot-application.log
  logging.pattern.file=%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx
  #配置使用的日志名 以及打印规则
  
                                                          4.集成服务调配
第一步:导入openfeign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
第二步:在提供服务和需要服务的启动类上添加@EnableFeignClients注解
第三步:创建接口如下
@FeignClient("eureka 客户端id 即提供服务客户端id")
public interface testt {
    //需要使用的接口
    @RequestMapping("/test")
    String test();
}

第三步;使用@Autowired 注入即可

 
                                                          5.集成安全插件Spring Security
(ps:可以选择单独做一个项目然后每个引入 或者每个项目单独配置)
配置安全插件后 客户端向服务端注册需要在地址前面加上账号密码例如:
http://账号:密码@${server.address}:8082/admin
格式是http://账号:密码@ip:域名

1.配置安全插件
import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.security.authentication.AuthenticationManager;
        import org.springframework.security.config.annotation.web.builders.HttpSecurity;
        import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
        import org.springframework.security.config.http.SessionCreationPolicy;
        import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
        import org.springframework.security.crypto.password.PasswordEncoder;
        import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //密码生产器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //登录成功处理
    @Autowired
    private CoverAuthenticationSuccessHandler coverAuthenticationSuccessHandler;

    //登录失败处理
    @Autowired
    private CoverAuthenticationFailureHandler coverAuthenticationFailureHandler;

    //退出登录成功处理
    @Autowired
    private CoverLogoutSuccessHandler coverLogoutSuccessHandler;

    //自定义过滤器
    @Autowired
    private CoverJwtAuthorizationTokenFilter coverJwtAuthorizationTokenFilter;

    //未登录时处理
    @Autowired
    private CoverAuthenticationEntryPoint coverAuthenticationEntryPoint;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                //permitAll允许全部权限访问或者hasAnyRole限制角色
                .antMatchers("/signIn").permitAll()
                .antMatchers("/login").permitAll()
                //排除上面外全部需要认证后访问
                .anyRequest().authenticated()
                .and().formLogin().successHandler(coverAuthenticationSuccessHandler).failureHandler(coverAuthenticationFailureHandler)
                .and().logout().logoutSuccessHandler(coverLogoutSuccessHandler)
                .and().httpBasic().authenticationEntryPoint(coverAuthenticationEntryPoint)
                //禁止session 如果全部前后端分离可以禁用session
                /*
                   ALWAYS,//总是会新建一个Session。
                   NEVER,//不会新建HttpSession,但是如果有Session存在,就会使用它。
                   IF_REQUIRED,//如果有要求的话,会新建一个Session。
                   STATELESS;//这个是我们用的,不会新建,也不会使用一个HttpSession。
                 */
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                .and().csrf().disable().cors()
                /**
                 DENY 只要使用frame等标签,都无法显示
                 SAMEORIGIN 只要是同源,可以显示html
                 ALLOW只要是允许的url,可以显示html
                 */
                .and().headers().frameOptions().sameOrigin();

        http.addFilterBefore(coverJwtAuthorizationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    //默认身份管理器
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

2.配置登录

        import lombok.extern.log4j.Log4j2;
        import lombok.val;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.security.authentication.BadCredentialsException;
        import org.springframework.security.core.authority.AuthorityUtils;
        import org.springframework.security.core.userdetails.User;
        import org.springframework.security.core.userdetails.UserDetails;
        import org.springframework.security.core.userdetails.UserDetailsService;
        import org.springframework.security.core.userdetails.UsernameNotFoundException;
        import org.springframework.stereotype.Component;

        import java.util.regex.Pattern;

@Component
@Log4j2
public class CoverUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //账号是否未失效
        boolean enabled = true;
        //账号是否未过期
        boolean accountNonExpired = true;
        //凭证是否未过期
        boolean credentialsNonExpired = true;
        //账号是否未锁定
        boolean accountNonLocked = true;
        if (! Pattern.matches("[0-9]*", username)) {
        //校验账号格式
        }
        if (username=="xxxx"){
            //账号是否存在
        }
        //获取账号信息
        /**
         * 用户名
         * 通过密码生产器生产后的密码
         * 用户的权限组
         */
        String[] roles=new String[]{};
        return new User(username,passwordEncoder.encode("xxxxxxx"), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, AuthorityUtils.createAuthorityList(roles));
    }
}

配置自定义过滤器

//登录成功 
implements AuthenticationSuccessHandler
//登录失败
 implements AuthenticationFailureHandler
//退出登录成功
implements LogoutSuccessHandler
//还未登录时
implements AuthenticationEntryPoint
//自定义过滤器
extends OncePerRequestFilter

 

 
 
posted @ 2022-04-07 16:45  小小怪l  阅读(508)  评论(0编辑  收藏  举报