新增案例子系统(hello),使用工具:IDEA

创建微服务子系统

1、右键【qingfeng-server】->New->Module…
image.png
2、选择Maven,新建maven子模块项目
image.png
3、父节点选择:qingfeng-server,子模块名称:qingfeng-server-hello
image.png
4、选择本地的maven安装地址及相关配置,点击完成。
image.png
5、创建完成后会在qingfeng-server中显示刚刚创建的子业务系统:qingfeng-server-hello
image.png

完善微服务子系统

1、基础调整

删除test下的AppTest.java ,在src/main下新建:resources 文件夹。
image.png

2、配置pom.xml

因为qingfeng-server-hello继承与qingfeng-server父模块,在父模块中的配置的jar会继承到子模块中,所以子模块设置如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <parent>
  5. <artifactId>qingfeng-server</artifactId>
  6. <groupId>com.qingfeng</groupId>
  7. <version>1.0-SNAPSHOT</version>
  8. </parent>
  9. <modelVersion>4.0.0</modelVersion>
  10. <artifactId>qingfeng-server-hello</artifactId>
  11. <name>qingfeng-server-hello</name>
  12. <description>qingfeng-Server-Hello案例服务模块</description>
  13. <build>
  14. <plugins>
  15. <plugin>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-maven-plugin</artifactId>
  18. </plugin>
  19. </plugins>
  20. </build>
  21. </project>

3、修改主入口文件

将App.java ,修改成:ServerHelloApplication.java
@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)

开启springsecurity
@EnableCloudApplication #自定义注入集合,如下图:
image.png

  1. package com.qingfeng;
  2. import com.qingfeng.annotation.EnableCloudApplication;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  6. /**
  7. * @ProjectName ServerHelloApplication
  8. * @author Administrator
  9. * @version 1.0.0
  10. * @Description TODO
  11. * @createTime 2021/4/19 0019 12:49
  12. */
  13. @SpringBootApplication
  14. @EnableGlobalMethodSecurity(prePostEnabled = true)
  15. @EnableCloudApplication
  16. public class ServerHelloApplication {
  17. public static void main(String[] args) {
  18. SpringApplication.run(ServerHelloApplication.class, args);
  19. }
  20. }

4、新建ServerHelloResourceServerConfigure

在com.qingfeng下新建:configure目录,新增:ServerHelloResourceServerConfigure.java (权限配置)

  1. package com.qingfeng.configure;
  2. import com.qingfeng.handler.MyAccessDeniedHandler;
  3. import com.qingfeng.handler.MyAuthExceptionEntryPoint;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  7. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  8. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  9. import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
  10. /**
  11. * @ProjectName ServerHelloResourceServerConfigure
  12. * @author Administrator
  13. * @version 1.0.0
  14. * @Description TODO
  15. * @createTime 2021/4/19 0019 12:54
  16. */
  17. @Configuration
  18. @EnableResourceServer
  19. public class ServerHelloResourceServerConfigure extends ResourceServerConfigurerAdapter {
  20. @Autowired
  21. private MyAccessDeniedHandler accessDeniedHandler;
  22. @Autowired
  23. private MyAuthExceptionEntryPoint exceptionEntryPoint;
  24. @Override
  25. public void configure(HttpSecurity http) throws Exception {
  26. http.csrf().disable()
  27. .requestMatchers().antMatchers("/**")
  28. .and()
  29. .authorizeRequests().antMatchers("/actuator/**").permitAll()
  30. .and()
  31. .authorizeRequests()
  32. .antMatchers("/**").authenticated();
  33. }
  34. @Override
  35. public void configure(ResourceServerSecurityConfigurer resources) {
  36. resources.authenticationEntryPoint(exceptionEntryPoint)
  37. .accessDeniedHandler(accessDeniedHandler);
  38. }
  39. }

5、新建GlobalExceptionHandler

新建handler目录,新增:GlobalExceptionHandler.java (全局异常配置)

  1. package com.qingfeng.handler;
  2. import org.springframework.core.Ordered;
  3. import org.springframework.core.annotation.Order;
  4. import org.springframework.web.bind.annotation.RestControllerAdvice;
  5. /**
  6. * @ProjectName GlobalExceptionHandler
  7. * @author Administrator
  8. * @version 1.0.0
  9. * @Description TODO
  10. * @createTime 2021/4/19 0019 12:57
  11. */
  12. @RestControllerAdvice
  13. @Order(value = Ordered.HIGHEST_PRECEDENCE)
  14. public class GlobalExceptionHandler extends BaseExceptionHandler {
  15. }

6、新建HelloController

新建controller目录,新增HelloController.java 测试。

  1. package com.qingfeng.controller;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.security.access.prepost.PreAuthorize;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import java.security.Principal;
  7. /**
  8. * @ProjectName TestController
  9. * @author qingfeng
  10. * @version 1.0.0
  11. * @Description TODO
  12. * @createTime 2021/4/3 0003 20:29
  13. */
  14. @Slf4j
  15. @RestController
  16. public class HelloController {
  17. /**
  18. * @title index
  19. * @description 首页
  20. * @author Administrator
  21. * @updateTime 2021/4/19 0019 13:00
  22. */
  23. @GetMapping("index")
  24. public String hello(String name){
  25. log.info("青锋欢迎您!!!");
  26. System.out.println("青锋hello模块");
  27. return "青锋欢迎您!!!";
  28. }
  29. /**
  30. * @title userAdd
  31. * @description 权限测试
  32. * @author Administrator
  33. * @updateTime 2021/4/19 0019 13:00
  34. */
  35. @GetMapping("userAdd")
  36. @PreAuthorize("hasAnyAuthority('user:add')")
  37. public String userAdd(){
  38. return "拥有'user:add'权限";
  39. }
  40. /**
  41. * @title user
  42. * @description 获取当前登录用户
  43. * @author Administrator
  44. * @updateTime 2021/4/19 0019 13:00
  45. */
  46. @GetMapping("user")
  47. public Principal user(Principal principal) {
  48. return principal;
  49. }
  50. }

7、新建banner.txt

在resources 下新建:banner.txt

  1. ____ _ ______
  2. / __ \ (_) | ____|
  3. | | | | _ _ __ __ _ | |__ ___ _ __ __ _
  4. | | | || || '_ \ / _` || __|/ _ \| '_ \ / _` |
  5. | |__| || || | | || (_| || | | __/| | | || (_| |
  6. \___\_\|_||_| |_| \__, ||_| \___||_| |_| \__, |
  7. __/ | __/ |
  8. |___/ |___/
  9. 青锋剑在手-天下任你走 2020-V1.0
  10. ${spring.application.name}
  11. Spring-Boot: ${spring-boot.version}

8、新建bootstrap.yml

在resources下新建:bootstrap.yml

  1. spring:
  2. application:
  3. name: qingfeng-Server-Hello
  4. cloud:
  5. nacos:
  6. discovery:
  7. server-addr: localhost:8001
  8. config:
  9. server-addr: localhost:8001
  10. group: DEFAULT_GROUP
  11. prefix: qingfeng-server-hello
  12. file-extension: yaml
  13. logging:
  14. level:
  15. com:
  16. alibaba:
  17. cloud:
  18. nacos:
  19. client:
  20. NacosPropertySourceBuilder: error

9、新建logback-spring.xml

在resources下新建:logback-spring.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration scan="true" scanPeriod="60 seconds" debug="false">
  3. <contextName>qingfeng</contextName>
  4. <springProperty scope="context" name="springAppName" source="spring.application.name"/>
  5. <property name="log.path" value="log/qingfeng-server-hello" />
  6. <property name="log.maxHistory" value="15" />
  7. <property name="log.colorPattern" value="%magenta(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%-5level) %boldCyan([${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]) %yellow(%thread) %green(%logger) %msg%n"/>
  8. <property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level [${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}] %thread %logger %msg%n"/>
  9. <!--输出到控制台-->
  10. <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
  11. <encoder>
  12. <pattern>${log.colorPattern}</pattern>
  13. </encoder>
  14. </appender>
  15. <!--输出到文件-->
  16. <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
  17. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  18. <fileNamePattern>${log.path}/info/info.%d{yyyy-MM-dd}.log</fileNamePattern>
  19. <MaxHistory>${log.maxHistory}</MaxHistory>
  20. </rollingPolicy>
  21. <encoder>
  22. <pattern>${log.pattern}</pattern>
  23. </encoder>
  24. <filter class="ch.qos.logback.classic.filter.LevelFilter">
  25. <level>INFO</level>
  26. <onMatch>ACCEPT</onMatch>
  27. <onMismatch>DENY</onMismatch>
  28. </filter>
  29. </appender>
  30. <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
  31. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  32. <fileNamePattern>${log.path}/error/error.%d{yyyy-MM-dd}.log</fileNamePattern>
  33. </rollingPolicy>
  34. <encoder>
  35. <pattern>${log.pattern}</pattern>
  36. </encoder>
  37. <filter class="ch.qos.logback.classic.filter.LevelFilter">
  38. <level>ERROR</level>
  39. <onMatch>ACCEPT</onMatch>
  40. <onMismatch>DENY</onMismatch>
  41. </filter>
  42. </appender>
  43. <root level="debug">
  44. <appender-ref ref="console" />
  45. </root>
  46. <root level="info">
  47. <appender-ref ref="file_info" />
  48. <appender-ref ref="file_error" />
  49. </root>
  50. </configuration>

10、配置Nacos ,新增qingfeng-server-hello

image.png

  1. server:
  2. port: 8206
  3. spring:
  4. boot:
  5. admin:
  6. client:
  7. url: http://localhost:8401
  8. username: qingfeng
  9. password: 123456
  10. zipkin:
  11. sender:
  12. type: rabbit
  13. sleuth:
  14. sampler:
  15. probability: 1
  16. rabbitmq:
  17. host: localhost
  18. port: 5672
  19. username: qingfeng
  20. password: 123456
  21. autoconfigure:
  22. exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration
  23. security:
  24. oauth2:
  25. resource:
  26. id: ${spring.application.name}
  27. user-info-uri: http://localhost:8301/auth/user
  28. feign:
  29. hystrix:
  30. enabled: true
  31. hystrix:
  32. shareSecurityContext: true
  33. info:
  34. app:
  35. name: ${spring.application.name}
  36. description: "@project.description@"
  37. version: "@project.version@"
  38. management:
  39. endpoints:
  40. web:
  41. exposure:
  42. include: '*'
  43. endpoint:
  44. health:
  45. show-details: ALWAYS
  46. logging:
  47. level:
  48. com.alibaba.nacos.client: error

11、修改qingfeng-gateway.yaml

image.png

  1. - id: qingfeng-Server-Hello
  2. uri: lb://qingfeng-Server-Hello
  3. predicates:
  4. - Path=/hello/**
  5. filters:
  6. - name: Hystrix
  7. args:
  8. name: hellofallback
  9. fallbackUri: forward:/fallback/qingfeng-Server-Hello

配置完成!

启动微服务子系统

项目启动

image.png

获取验证码

http://localhost:8301/auth/captcha?key=qingfeng
image.png

获取access_token

http://localhost:8301/auth/oauth/token?grant_type=password&username=admin&password=123456&key=qingfeng&code=6548
image.png
值为Basic加空格加client_id:client_secret(就是在AuthorizationServerConfigure类configure(ClientDetailsServiceConfigurer clients)方法中定义的client和secret)经过base64加密后的值(可以使用http://tool.oschina.net/encrypt?type=3):
image.png

测试index

image.png
image.png

获取当前用户

image.png