第四节 IDEA常用模板设置

亮子 2021-07-15 02:40:24 17827 0 0 0

1、mybatis plus

1)、依赖

xml-mybatis

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.2</version>
        </dependency>

2)、配置文件

set-mybatis

spring.datasource.url=jdbc:mysql://localhost:3306/db_blog?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
mybatis.typeAliasesPackage=com.shenmazong.servershopuser.mapper
mybatis.mapperLocations=classpath:/mapper/*.xml
logging.level.com.shenmazong.servershopuser.mapper=debug

3)、分页拦截器

code-page

@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}

2、eureka服务器

1)、依赖

xml-eureka

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

2)、配置文件

set-eureka

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://localhost:6060/eureka/

3、zuul网关

1)、依赖

xml-zuul

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>

2)、配置文件

set-zuul

# eureka client
eureka.client.service-url.defaultZone=http://localhost:6060/eureka/
eureka.instance.prefer-ip-address=true
## server-blog-user
zuul.routes.server-user.service-id=server-blog-user
zuul.routes.server-user.path=/user/**
## server-blog-article
zuul.routes.server-article.service-id=server-blog-article
zuul.routes.server-article.path=/article/**

# 跨域配置
# 将网关层的CORS放开
## 参考2
zuul:
   sensitiveHeaders: Cookie,Set-Cookie
   ignored-headers: Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Access-Control-Allow-Methods
## 参考1
zuul:
#需要忽略的头部信息,不在传播到其他服务
  sensitive-headers: Access-Control-Allow-Origin
  ignored-headers: Access-Control-Allow-Origin,H-APP-Id,Token,APPToken

3)、跨域配置类

java-zuul-cors

  @Bean
  public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

4)、zuul过滤器

java-zuul-filter

public class LoginZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getHeader("token");

        return null;
    }
}

4、JWT

1)、依赖

xml-jwt

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

2)、token生成和解析

java-jwt

        JwtBuilder builder = Jwts.builder();
        builder.setId("1");
        builder.setSubject("a");
        builder.setIssuedAt(new Date());
        long now = System.currentTimeMillis();
        long exp = now+1000*300;
        builder.setExpiration( new Date( exp ) );
        builder.claim( "roles","admin" );
        builder.signWith(SignatureAlgorithm.HS256,"shenmazong");
        String token = builder.compact();

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("shenmazong")
                    .parseClaimsJws(token)
                    .getBody();
            System.out.println("id=" + claims.getId());
            System.out.println("roles=" + claims.get("roles"));
        }
        catch (ExpiredJwtException e) {
            System.out.println("token expired");
        } catch (SignatureException e) {
            System.out.println("token signature error");
        } catch (Exception e) {
            System.out.println("token error");
        }

4、openfeign

1)、依赖

xml-openfeign

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

2)、调用代码

java-openfeign

// @EnableFeignClients
@FeignClient(value = "server-blog-article")
@Component(value = "iUserService")
public interface IUserService {
    @RequestMapping(value = "/hello")
    public String hello();
}

5、hystrix

1)、依赖

xml-hystrix

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

2)、代码调用

java-hystrix

    // @EnableCircuitBreaker
    @RequestMapping(value = "/getArticle")
    @ResponseBody
    @HystrixCommand(fallbackMethod = "fallGetArticle")
    public Object getArticle(@RequestParam("id") Integer id) {
        return null;
    }

6、swagger

1)、依赖

xml-swagger

        <!--    swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
                <exclusions>
                    <exclusion>
                        <groupId>io.swagger</groupId>
                        <artifactId>swagger-models</artifactId>
                    </exclusion>
                </exclusions>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.swagger/swagger-models -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.22</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>

2)、配置类

java-swagger

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.mazong.serverbloguser";
    public static final String VERSION = "1.0.0";
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("shenmazong")
                .description("user api")
                .version(VERSION)
                .termsOfServiceUrl("http://www.shenmazong.com")
                .build();
    }
}