Commit ca27f4bf by 刘宇峰

脚手架项目迁移git

0 parents
Showing 414 changed files with 4671 additions and 0 deletions
# glsx-rest-admin(微服务快速开发的脚手架)
## 背景&目标
当前新建项目时,配置文件往往都是从其它项目拷贝过来,拷贝时很容易踩坑,并且不容易定位问题。尤其对新人来说由于在对公司项目结构、基础中间件、配置还不了解的情况下,会浪费很多不必要的时间。故,希望通过脚手架解决此痛点,达到如下几个基本目标:
1. 统一规范工程项目&代码层次结构——约定大于配置;
2. 提升工作效率——脚手架&代码生成器&自定义插件;
3. 降低项目维护成本——易于组内成员相互协防;
另,发现当前各自创建的项目,存在如下几个现象,希望借机推进组内代码规范落地:
1. 项目&包层次结构不统一;
2. 配置文件命名、存放位置不统一;
3. 类命名不统一(有的叫entity,有的叫BO,有的叫Domain;有的叫job,有的叫crane,有的叫schedule;接口命名有的I开头,有的无I开头);
希望在项目模板(脚手架)中在每个层次环节代码中直接给予相应的Demo,以此达到规范引导作用。
## 项目介绍
基于 Spring Cloud 完整的微服务架构的一个脚手架项目
## 技术栈
> 权限认证
>
> > Jwt
> 配置中心
>
> > Alibaba nacos
> 服务注册与发现
>
> > Alibaba nacos
> 分布式链路追踪
>
> > sleuth
> >
> > zipkin
> 网关
>
> > SpringCloud Gateway
> 流量控制、熔断降级
>
> > Alibaba sentinel
> Http声名式转发
>
> > Feign
> >
> > RestTemplate
> >
> > WebClient
> 持久层
>
> > mybatis
> >
> > pagehelper
> >
> > tk-mapper
> >
> > Jpa
> 数据存储
>
> > MySQL
> >
> > Redis
> >
> > MongoDB
> 文件服务
>
> > Fastdfs
> >
> > Minio
> 消息中间件
>
> > Kafka
## 项目结构
## 模块说明
![架构图](https://images.gitee.com/uploads/images/2019/0528/205306_9a8b8d83_1899222.png "1.png")
## 项目涉及服务组件
#### 1. nacos
Nacos是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。Nacos 支持几乎所有主流类型的服务的发现、配置和管理:
* Kubernetes Service
* gRPC & Dubbo RPC Service
* Spring Cloud RESTful Service
官网:https://nacos.io/
github:https://github.com/alibaba/nacos/releases
```sh
sh startup.sh -m standalone
```
开发环境部署地址:/data/nacos
开发环境访问地址:http://192.168.0.63:8848/nacos/
账号密码:nacos/nacos
#### 2. zipkin
官网:https://zipkin.io/
github:https://github.com/openzipkin/zipkin
```sh
nohup java -jar zipkin-server-2.12.9-exec.jar &
```
关于zipkin的基本使用请查看其他文章或者自行百度
开发部署:http://192.168.0.63:9411/zipkin/
开发环境部署地址:/data/zipkin
开发环境访问地址:http://192.168.0.63:9411/zipkin/
#### 3. sentinel-dashboard
github:https://github.com/alibaba/Sentinel
https://dl.bintray.com/openzipkin/maven/io/zipkin/java/zipkin-server/2.12.9/
```sh
nohup java -Dserver.port=8718 -Dcsp.sentinel.dashboard.server=localhost:8718 -Dproject.name=sentinel-dashboard -Dcsp.sentinel.api.port=8719 -jar sentinel-dashboard-1.7.2.jar &
```
开发环境部署地址:/data/sentinel
开发环境访问地址:http://192.168.0.63:8718/#/login
账号密码:sentinel/sentinel
![](https://upload-images.jianshu.io/upload_images/5417792-ae78d6da78d48b31.png)
#### 4. spring-cloud-gateway-server
svn地址:svn://192.168.3.233/frms/code/glsx-archetype/glsx-archetype/glsx-archetype-parent/glsx-rest-admin-gateway-server
![](https://img-blog.csdnimg.cn/20191208161419451.png)
#### 4. spring-boot-admin-server
svn地址:svn://192.168.3.233/frms/code/glsx-archetype/glsx-archetype/glsx-archetype-parent/glsx-rest-admin-monitor-server
![](https://oscimg.oschina.net/oscnet/up-a38e9bb6b0d08cccf3ab9c6c99b4b398650.png)
开发环境部署地址:/data/webserver/glsx-rest-admin-monitor-server-1.0-SNAPSHOT
开发环境访问地址:http://192.168.0.63:8769/applications
## 脚手架项目运行调试
#### SVN地址
svn地址:svn://192.168.3.233/frms/code/glsx-archetype/glsx-archetype/glsx-archetype-parent/glsx-rest-admin
[脑图](https://www.kdocs.cn/view/l/cDUsOKQht? "项目引用框架结构")
### 添加配置中心
1. 打开nacos的管理中心(http://192.168.0.63:8848/nacos/#/login)
2. 新增data-id为${prefix}-${spring.profile.active}.${file-extension}
* prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置。
* spring.profile.active 即为当前环境对应的 profile,详情可以参考 Spring Boot文档。注意:当 spring.profile.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 prefix.{file-extension}
* file-extension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 properties 和 yaml 类型。
关于配置格式,通俗的讲,即为file-extension。如配置格式选择properties格式,则DataId后缀必须为properties(注意yaml,可写为yml,与yaml同义,但与bootstrap配置中的file-extension必须一致),配置内容也必须按照properties格式编写。
<pre>
<code>
server.port=8828
server.servlet.context-path=/${spring.application.name}
</code>
</pre>
[glsx-rest-admin-DEV.properties](http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin-DEV.properties&group=DEV_GROUP "脚手架项目配置")
3. 执行Application.main()启动项目
### 修改网关服务网关配置
<pre>
<code>
#glsx-rest-admin
spring.cloud.gateway.routes[0].id=glsx-rest-admin
spring.cloud.gateway.routes[0].uri=lb://glsx-rest-admin
spring.cloud.gateway.routes[0].predicates[0]=Path=/glsx-rest-admin/**
spring.cloud.gateway.routes[0].filters[0]=StripPrefix=0
</code>
</pre>
[glsx-rest-admin-gateway-DEV.properties](http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin-gateway-DEV.properties&group=DEV_GROUP "网关服务配置")
##脚手架
a. 构建脚手架命令
<pre><code>mvn archetype:create-from-project</code></pre>
b. 安装脚手架命令
<pre><code>
cd target\generated-sources\archetype
mvn clean install
</code></pre>
c. 发布
<pre><code>mvn deploy</code></pre>
groupId:上传到私服的groupId<br>
artifactId:上传到私服的artifactId<br>
version:上传到私服的version<br>
file:jar包的本地路径<br>
url: 你的maven私服地址<br>
repositoryId:setting.xml配置的server id
jar复制到非仓库目录,不然可能会发布失败
OR
<pre><code>mvn deploy:deploy-file -DgroupId=com.glsx -DartifactId=glsx-rest-admin-archetype-archetype -Dversion=1.0-SNAPSHOT -Dpackaging=jar -Dfile=D:\glsx-rest-admin-archetype-archetype-1.0-SNAPSHOT.jar -Durl=http://192.168.3.233/nexus/content/repositories/snapshots -DrepositoryId=nexus-snapshots</code></pre>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-rest-admin-archetype</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>glsx-rest-admin-api</artifactId>
<dependencies>
<!-- feign -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.admin.api;
import cn.com.glsx.admin.services.userservice.model.UserBO;
import cn.com.glsx.admin.services.userservice.model.UserDTO;
import com.github.pagehelper.PageInfo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Map;
/**
* @author payu
*/
@FeignClient(name = "glsx-rest-admin", contextId = "usercenter", path = "/api/user/", decode404 = true)
public interface UserCenterFeignClient {
/**
* 一、FeignClients使用注意事项:
* 1. @EnableFeignClients 默认扫描 xxxxApplication启动入口 所在包路径下的 @FeignClient bean,若无法扫描到, 可以在使用Feign调用外部模块的api时候,
* 需要在引用服务中 xxxxApplication 中的 `@EnableFeignClients(basePackages = "cn.tendyron.customer")` 添加外部包需要扫描FeignClient的路径,否则无法注入bean
* 2. @FeignClient 声明的类,使用 spring.application.name 作为 name配置 @FeignClient(name="xxxx"),如果想保留 context-path , 则需要配置 path 属性 ,如:@FeignClient(name="xxxx" , path="xxxx(context-path)")
* 3. @FeignClient 接口对应的实现类,需要使用 @RestController注解 声明
* 4. mapper注解不支持 : @GetMapping,@PostMapping , 参数要加 @RequestParam(“xxx”)
* 5. FeignClient 调用,实质是httpClient调用 ,若我们暴露的接口api,声明了对应的 http mapper 信息,在调用方调用时候,通过代理 发起了 http请求,到服务提供方对应的http服务上去,所以在服务提供方的接口,可以使用 @RestController
* 来声明接口的 实现,否则调用方无法找到 http 对应的路径,会报404 ;
* 或者 根据 api 声明的http 信息,构建一个 Controller ,再来调用接口的实现类,但是这样不太方便;
* 6.FeignClient是一个“客户端”,它是用来发起请求的,不是提供服务的。
*
*
* 二、fallback 几种模式:
* 1.EchoCenterFeignServiceFallback.class 直接fallback,获取不到HTTP请求错误状态码和信息
* 2.EchoCenterFeignFactory.class 特定类型工厂模式
* 3.FunFallbackFactory 使用统一的工厂模式处理
*
*
* 三、性能问题
* 1.Feign是一个http请求调用的轻量级框架,基于http协议,性能不如rpc
* 2.可以为Feign配置连接池,配合使用okhttp等
*/
/**
* 测试Feign Get ,普通处理
* 注意: @RequestParam("xx") 注解一定要写,而且属性名xx不能省略
*/
@GetMapping("/echo")
String echo(@RequestParam("message") String message);
@GetMapping("/search")
PageInfo<UserDTO> search(@RequestParam Map<String, Object> params);
@PostMapping(value = "/add")
UserDTO add(@RequestBody @Valid UserBO userBO);
@PostMapping(value = "/edit")
int edit(@RequestBody @Valid UserBO userBO);
@GetMapping(value = "/info/{id}")
UserDTO info(@PathVariable("id") Long id);
}
package cn.com.glsx.admin.services.userservice.model;
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* @author payu
*/
@Data
public class UserBO {
private Long id;
@NotBlank
private String username;
private String realName;
@NotBlank
private String password;
@NotBlank
private String phone;
private String remark;
private Long[] roleIds;
}
package cn.com.glsx.admin.services.userservice.model;
import lombok.Data;
/**
* @author payu
*/
@Data
public class UserDTO {
private Long id;
private String username;
private String realname;
private String password;
private String phone;
private String remark;
private Long[] roleIds;
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-rest-admin-archetype</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>glsx-rest-admin-dao</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--mybatis 逆向生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<!-- <phase>package</phase>-->
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!-- 自动生成的配置 -->
<configurationFile>src/main/resources/config/generatorConfig.xml</configurationFile>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package com.glsx.vasp.modules.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Accessors(chain = true)
@Data
@Entity
@Table(name = "d_user")
public class User extends BaseEntity {
/**
* 帐号
*/
@Column(name = "account", length = 64)
private String account;
/**
* 密码
*/
@JsonIgnore
@Column(name = "password", length = 128)
private String password;
/**
* 用户名
*/
@Column(name = "username", length = 64)
private String username;
/**
* (真实)姓名
*/
@Column(name = "realname", length = 64)
private String realname;
/**
* 手机号
*/
@Column(name = "phone", length = 20)
private String phone;
/**
* 头像链接
*/
@Column(name = "avatar", length = 150)
private String avatar;
/**
* 加密盐
*/
private String salt;
}
package com.glsx.vasp.modules.mapper;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import com.glsx.vasp.modules.entity.User;
import com.glsx.vasp.modules.model.UserSearch;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper extends CommonBaseMapper<User> {
List<User> selectList(UserSearch search);
User selectByPhone(String phone);
void logicDeleteById(Long id);
}
\ No newline at end of file \ No newline at end of file
package com.glsx.vasp.modules.model;
import cn.hutool.db.Page;
import lombok.Data;
/**
* @author payu
*/
@Data
public class UserSearch extends Page {
private String term;
}
//package com.glsx.vasp.modules.repository;
//
//import com.glsx.vasp.modules.entity.User;
//import java.io.Serializable;
//
///**
// * UserRepository JPA
// */
//public interface IUserRepository extends BaseRepository<User, Long>, Serializable {
//
// User findByUsername(String username);
//
//}
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!-- <classPathEntry location="F://jdbc//mysql-connector-java-8.0.18.jar"/>-->
<!-- 一个数据库一个context -->
<context id="DB2Tables" targetRuntime="Mybatis3">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true"/>
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 配置 tk.mybatis 插件 -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.glsx.plat.mybatis.mapper.CommonBaseMapper"/>
</plugin>
<!--配置生成注释信息,最多配置一个 -->
<commentGenerator>
<!-- 阻止生成注释包含时间戳 默认为false -->
<property name="suppressDate" value="true"/>
<!-- 注释是否添加数据库表的备注信息 默认为false -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- jdbc连接-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.0.39:3306/seata_storage?serverTimeZone=Shanghai&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
userId="root"
password="123456">
<!--防止生成其他库同名表-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="cn.com.payu.modules.entity" targetProject="src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值去掉前后空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapper.xml文件存放地址 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成接口dao type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="cn.com.payu.modules.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
<table tableName="t_storage" domainObjectName="Storage" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.glsx.vasp.modules.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.glsx.vasp.modules.entity.User">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="phone" jdbcType="VARCHAR" property="phone"/>
<result column="wx_openid" jdbcType="VARCHAR" property="wxOpenid"/>
<result column="mini_openid" jdbcType="VARCHAR" property="miniOpenid"/>
<result column="enable_status" jdbcType="TINYINT" property="enableStatus"/>
<result column="delete_status" jdbcType="TINYINT" property="deleteStatus"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
</resultMap>
<select id="selectList" resultMap="BaseResultMap">
select * from d_user
</select>
<select id="selectByPhone" parameterType="java.lang.String" resultMap="BaseResultMap">
select * from d_user where phone = #{phone}
</select>
<update id="logicDeleteById" parameterType="java.lang.Long">
update d_user set delete_status = -1 where id = #{id}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-admin-archetype</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<description>Microservice Scaffolding Project Base on Spring Cloud</description>
<artifactId>glsx-rest-admin</artifactId>
<dependencies>
<!-- 运行环境上下文 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等 ,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- dao示例 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-admin-dao</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-admin-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-service-echocenter-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"cn.com.glsx.admin.api", "cn.com.glsx.echocenter.api"})
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.admin.common.constant;
import com.glsx.plat.core.constant.BasicConstants;
/**
* 〈一句话功能简述〉<br>
* 公共常量类
*
* @author liuyf
* @since 1.0.0
*/
public final class Constants extends BasicConstants {
public final static String SERVER_NAME = "glsx_rest_admin";
}
package cn.com.glsx.admin.common.exception;
import com.glsx.plat.exception.SystemMessage;
import lombok.Getter;
import lombok.Setter;
/**
* @author payu
*/
@Setter
@Getter
public class AdminException extends RuntimeException {
private int errorCode;
public AdminException() {
}
public AdminException(String message) {
super(message);
}
public AdminException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public AdminException of(SystemMessage message) {
return new AdminException(message.getCode(), message.getMsg());
}
public AdminException(Throwable cause) {
super(cause);
}
public AdminException(String message, Throwable cause) {
super(message, cause);
}
}
package cn.com.glsx.admin.common.exception;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.ExceptionLevel;
import com.glsx.plat.exception.GlobalExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理
*
* @author payu
*/
@Slf4j
@RestControllerAdvice
public class AdminExceptionHandler extends GlobalExceptionHandler {
@ExceptionHandler(AdminException.class)
public R handleAdminException(AdminException e) {
return R.error(e.getMessage());
}
/**
* 引入Feign服务的话
*
* @param e
* @return
*/
// @ExceptionHandler(FeignException.class)
// public R handleFeignException(FeignException e) {
// return R.error(e.status(), e.getMessage());
// }
/**
* Mybatis BindingException
*
* @param e
* @return
*/
@ExceptionHandler(BindingException.class)
public R handleBindingException(BindingException e) {
return R.error(e.getMessage());
}
@Override
protected void saveException(Exception e, ExceptionLevel level) {
super.saveException(e, level);
}
}
package cn.com.glsx.admin.config;
import cn.com.glsx.admin.modules.user.utils.JwtUser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.context.properties.UploadProperties;
import com.glsx.plat.web.interceptor.LogInterceptor;
import com.glsx.plat.web.interceptor.VisitInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* @author liuyf
* @Title WebConfig.java
* @Description 系统的配置相关文件,如拦截器,过滤器,跨域等
* @date 2019年7月18日 下午4:45:06
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private UploadProperties uploadProperties;
/**
* 基于MDC的简单的日志链路
*/
@Resource
private LogInterceptor logInterceptor;
/**
* 基于jwt的token认证
*/
@Resource
private VisitInterceptor<JwtUser> visitInterceptor;
/**
* 静态资源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/")
.addResourceLocations("classpath:/resources/")
.addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/public/")
.addResourceLocations("/dist/").addResourceLocations();
String path = uploadProperties.getBasePath();
registry.addResourceHandler("/files/**").addResourceLocations("file://" + path);
}
/**
* 使用此方法, 以下 spring-boot: jackson时间格式化 配置 将会失效
* spring.jackson.time-zone=GMT+8
* spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
* 原因: 会覆盖 @EnableAutoConfiguration 关于 WebMvcAutoConfiguration 的配置
*/
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = converter.getObjectMapper();
// 生成JSON时,将所有Long转换成String
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
// 时间格式化
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setDateFormat(new SimpleDateFormat(DateUtils.NORMAL_DATE_TIME_PATTERN));
// 设置格式化内容
converter.setObjectMapper(objectMapper);
converters.add(0, converter);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//1.加入的顺序就是拦截器执行的顺序,
//2.按顺序执行所有拦截器的preHandle
//3.所有的preHandle 执行完再执行全部postHandle 最后是postHandle
registry.addInterceptor(visitInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/")
.excludePathPatterns("/login")
.excludePathPatterns("/actuator/**")
.excludePathPatterns("/api/**")
.excludePathPatterns(uploadProperties.getFilepath());
registry.addInterceptor(logInterceptor).addPathPatterns("/**");
}
/**
* 有问题,建议用filter
* https://blog.csdn.net/weixin_33958585/article/details/88678712
*
* @param registry
*/
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**")
// .allowedOrigins(origins.split(","))
// .allowedHeaders("Authorization, Content-Type, X-Requested-With")
// .allowedMethods("POST, PUT, GET, OPTIONS, DELETE")
// .allowCredentials(true)
// .maxAge(3600);
// }
}
package cn.com.glsx.admin.modules;
import cn.com.glsx.admin.modules.user.service.UserService;
import com.glsx.plat.core.web.R;
import com.glsx.plat.web.controller.AbstractController;
import com.glsx.vasp.modules.entity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author liuyf
* @Title BaseController.java
* @Package com.glsx.vasp.controller
* @Description
* @date 2019年10月24日 下午2:24:00
*/
@RestController
public class BaseController extends AbstractController {
@Resource
private UserService userService;
/**
* 这个给Spring Boot Admin探测用
*
* @return
*/
@GetMapping(value = "/")
public R index() {
return R.ok("You get it!");
}
/**
* 从session中获取当前用户
*
* @return
*/
@Override
public User getSessionUser() {
User user = userService.getByToken();
if (user == null || StringUtils.isBlank(user.getPhone())) {
return null;
}
return user;
}
@Override
public Long getUserId() {
User user = getSessionUser();
if (user != null) {
return user.getId();
}
return null;
}
@Override
public String getAccount() {
User user = getSessionUser();
if (user != null) {
return user.getUsername();
}
return null;
}
/**
* 参数校验
*
* @param bindingResult
* @throws BindException
*/
protected void checkDTOParams(BindingResult bindingResult) throws BindException {
if (bindingResult.hasErrors()) {
throw new BindException(bindingResult);
}
}
}
package cn.com.glsx.admin.modules;
import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.core.web.R;
import cn.com.glsx.admin.modules.user.service.UserService;
import com.glsx.vasp.modules.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* @author payu
*/
@Slf4j
@RestController
public class LoginController {
@Resource
private UserService userService;
/**
* 登录
*/
@SysLog
@PostMapping(value = "/login")
public R login(@RequestParam String phone, @RequestParam String code) {
// User user = userService.findByPhone(phone);
User user = new User();
user.setPhone(phone);
String token = userService.createToken(user);
Map<String, Object> rtnMap = new HashMap<>();
rtnMap.put("token", token);
rtnMap.put("user", user);
return R.ok().data(rtnMap);
}
}
package cn.com.glsx.admin.modules.user.controller;
import cn.com.glsx.admin.api.UserCenterFeignClient;
import cn.com.glsx.admin.modules.user.converter.UserConverter;
import cn.com.glsx.admin.modules.user.service.UserService;
import cn.com.glsx.admin.services.userservice.model.UserBO;
import cn.com.glsx.admin.services.userservice.model.UserDTO;
import cn.com.glsx.echocenter.api.EchoCenterFeignClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.context.utils.validator.AssertUtils;
import com.glsx.vasp.modules.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;
/**
* 微服务应用在网关中处理统一返回体
*
* @author payu
*/
@Slf4j
@RestController
@RequestMapping(value = "/api/user")
public class UserApiController implements UserCenterFeignClient {
@Resource
private UserService userService;
@Resource
private EchoCenterFeignClient echoCenterFeignClient;
@Override
@GetMapping("/echo")
public String echo(@RequestParam String message) {
String echo = echoCenterFeignClient.echo(message);
return echo;
}
@Override
@GetMapping("/search")
public PageInfo<UserDTO> search(@RequestParam Map<String, Object> params) {
Integer pageNumber = (Integer) params.get("pageNumber");
Integer pageSize = (Integer) params.get("pageSize");
AssertUtils.isNull(pageNumber, "当前页数不能为空");
AssertUtils.isNull(pageSize, "分页大小不能为空");
PageHelper.startPage(pageNumber, pageSize);
PageInfo<UserDTO> list = userService.search(params);
return list;
}
@Override
@PostMapping(value = "/add")
public UserDTO add(@RequestBody @Valid UserBO userBO) {
User user = UserConverter.INSTANCE.bo2do(userBO);
User savedUser = userService.addUser(user);
UserDTO result = UserConverter.INSTANCE.do2dto(savedUser);
return result;
}
@Override
@PostMapping(value = "/edit")
public int edit(@RequestBody @Valid UserBO userBO) {
AssertUtils.isNull(userBO.getId(), "ID不能为空");
User user = UserConverter.INSTANCE.bo2do(userBO);
int editCnt = userService.editUser(user);
return editCnt;
}
@Override
@GetMapping(value = "/info/{id}")
public UserDTO info(@PathVariable("id") Long id) {
User user = userService.getById(id);
UserDTO result = UserConverter.INSTANCE.do2dto(user);
return result;
}
}
package cn.com.glsx.admin.modules.user.controller;
import cn.com.glsx.admin.modules.BaseController;
import cn.com.glsx.admin.modules.user.service.UserService;
import cn.com.glsx.admin.services.userservice.model.UserDTO;
import com.glsx.vasp.modules.model.UserSearch;
import cn.com.glsx.echocenter.api.EchoCenterFeignClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.core.web.R;
import com.glsx.vasp.modules.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* 单体应用Controller处理统一返回体
*
* @author payu
*/
@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController extends BaseController {
@Resource
private UserService userService;
@Resource
private EchoCenterFeignClient echoCenterFeignClient;
@GetMapping("/echo")
public R echo(@RequestParam String message) {
String echo = echoCenterFeignClient.echo(message);
return R.ok().data(echo);
}
@GetMapping("/search")
public R search(UserSearch search) {
PageHelper.startPage(search.getPageNumber(), search.getPageSize());
PageInfo<UserDTO> list = userService.search(search);
return R.ok().putPageData(list);
}
// @NoLogin
// @CheckSign
// @PostMapping(value = "/add")
// public R add(@RequestBody @Validated UserDTO userDTO) {
// User user = userDTO.convertTo();
// User savedUser = userService.addUser(user);
// UserDTO result = userDTO.convertFor(savedUser);
// return R.ok().data(result);
// }
//
// @PostMapping(value = "/edit")
// public R edit(@RequestBody @Validated UserDTO userDTO) {
// User user = userDTO.convertTo();
// User editUser = userService.editUser(user);
// UserDTO result = userDTO.convertFor(editUser);
// return R.ok();
// }
@GetMapping(value = "/info/{id}")
public R info(@PathVariable("id") Long id) {
User user = userService.getById(id);
return R.ok().data(user);
}
@GetMapping(value = "/info/phone")
public R info(String phone) {
User user = userService.findByPhone(phone);
return R.ok().data(user);
}
}
package cn.com.glsx.admin.modules.user.converter;
import cn.com.glsx.admin.services.userservice.model.UserBO;
import cn.com.glsx.admin.services.userservice.model.UserDTO;
import com.glsx.vasp.modules.entity.User;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
/**
* 解耦dao与api的实体映射
* 字段名不一样,用@Mapping来处理
* https://github.com/mapstruct/mapstruct-examples
*
* @author payu
*/
@Mapper
public interface UserConverter {
UserConverter INSTANCE = Mappers.getMapper(UserConverter.class);
@Mappings(@Mapping(source = "username", target = "username"))
UserDTO do2dto(User user);
@Mappings(@Mapping(source = "username", target = "username"))
User dto2do(UserDTO userDTO);
@Mappings(@Mapping(source = "realname", target = "realName"))
UserBO do2bo(User user);
@Mappings(@Mapping(source = "realName", target = "realname"))
User bo2do(UserBO userBO);
}
package cn.com.glsx.admin.modules.user.service;
import cn.com.glsx.admin.common.exception.AdminException;
import cn.com.glsx.admin.modules.user.converter.UserConverter;
import cn.com.glsx.admin.modules.user.utils.JwtUser;
import cn.com.glsx.admin.services.userservice.model.UserDTO;
import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.utils.ObjectUtils;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.jwt.util.JwtUtils;
import com.glsx.plat.web.utils.SessionUtils;
import com.glsx.vasp.modules.entity.User;
import com.glsx.vasp.modules.mapper.UserMapper;
import com.glsx.vasp.modules.model.UserSearch;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* @author liuyf
* @desc 用户信息
* @date 2019年10月24日 下午2:37:40
*/
@Service
public class UserService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private JwtUtils jwtUtils;
@Resource
private UserMapper userMapper;
public User getById(Long id) {
return userMapper.selectByPrimaryKey(id);
}
public User findByPhone(String phone) {
return userMapper.selectByPhone(phone);
}
public PageInfo<UserDTO> search(UserSearch search) {
List<User> userList = userMapper.selectList(search);
List<UserDTO> list = new ArrayList<>(userList.size());
userList.forEach(u -> list.add(UserConverter.INSTANCE.do2dto(u)));
return new PageInfo<>(list);
}
public PageInfo<UserDTO> search(Map<String, Object> params) {
UserSearch search = new UserSearch();
try {
BeanUtils.populate(search, params);
} catch (Exception e) {
return new PageInfo<>(new ArrayList<>());
}
return search(search);
}
public User addUser(User user) {
String password = user.getPassword();
// // uuid获取随机字符串,作为盐值。
// String salt = StringUtils.generateRandomCode(false, 4);
//
// //add Salt to password
// //user.getCredentialsSalt
// SimpleHash hash = new SimpleHash(hcm.getHashAlgorithmName(), password, salt, hcm.getHashIterations());
// //重新赋值
// user.setSalt(salt);
// user.setPassword(hash.toString());
// user.setEnableStatus(SysConstants.EnableStatus.enable.getCode());
// user.setCreateTime(new Date());
//todo 入库
return user;
}
public int editUser(User user) {
String password = user.getPassword();
//todo 更新入库
return 0;
}
public String createToken(User user) {
String jwtId = UUID.randomUUID().toString(); //JWT 随机ID,做为验证的key
JwtUser jwtUser = new JwtUser();
jwtUser.setJwtId(jwtId);
jwtUser.setUserId(String.valueOf(user.getId()));
jwtUser.setPhone(user.getPhone());
Map<String, String> userMap = (Map<String, String>) ObjectUtils.objectToMap(jwtUser);
return jwtUtils.createCachedToken(jwtId, userMap);
}
/**
* 根据Token获取Customer
*/
public User getByToken() {
String token = SessionUtils.request().getHeader(HttpHeaders.AUTHORIZATION);
if (StringUtils.isNullOrEmpty(token)) {
throw new AdminException(SystemMessage.ILLEGAL_ACCESS.getCode(), "登录已失效");
}
//解析token,反转成JwtUser对象
Map<String, Object> userMap = jwtUtils.parseClaim(token);
JwtUser jwtUser = null;
try {
jwtUser = (JwtUser) ObjectUtils.mapToObject(userMap, JwtUser.class);
} catch (Exception e) {
throw new AdminException(SystemMessage.ILLEGAL_ACCESS.getCode(), "登录已失效");
}
User user = new User();
user.setId(Long.valueOf(jwtUser.getUserId()));
user.setPhone(jwtUser.getPhone());
return user;
}
}
package cn.com.glsx.admin.modules.user.utils;
import com.glsx.plat.jwt.base.BaseJwtUser;
import lombok.Getter;
import lombok.Setter;
/**
* 用于jwt与数据库用户实体映射关联
*
* @author payu
*/
@Setter
@Getter
public class JwtUser extends BaseJwtUser {
private String phone;
@Override
public String getClazz() {
return this.getClass().getCanonicalName();
}
}
\ No newline at end of file \ No newline at end of file
spring.application.name=admin
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#server
server.port=8202
server.servlet.context-path=/${spring.application.name}
server.servlet.session.timeout=2592000
server.max-http-header-size=8192
server.tomcat.uri-encoding=UTF-8
server.tomcat.max-threads=1000
server.tomcat.min-spare-threads=30s
server.tomcat.basedir=/temp
#database
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.0.39:3306/gecc?serverTimeZone=Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
# Hikari will use the above plus the following to setup connection pooling
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=DatebookHikariCP
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
spring.data.redis.repositories.enabled = false
#redis config
spring.redis.host=192.168.0.39
spring.redis.port=6379
spring.redis.password=hhxredis
spring.redis.database=1
spring.redis.timeout=200000
#jwt config
jwt.config.header=Authorization
jwt.config.ttl=7200
jwt.config.key=5371f568a45e5ab1f442c38e0932aef24447139c
\ No newline at end of file \ No newline at end of file
#项目名称
spring.application.name=glsx-rest-admin
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=DEV_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
#spring.profiles.active=DEV
#配置格式
#spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-rest-admin-share.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8820"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="glsx-rest-admin"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file \ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="glsx-rest-admin"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import cn.com.glsx.admin.modules.user.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoApplicationTests {
@Autowired
private UserService userService;
@Test
public void testLogin() {
userService.findByPhone("13800138000");
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import cn.com.glsx.admin.modules.user.converter.UserConverter;
import cn.com.glsx.admin.services.userservice.model.UserDTO;
import com.glsx.vasp.modules.entity.User;
public class Test {
public static void main(String[] args) {
User user = new User();
user.setId(1L);
user.setUsername("Hollis");
user.setRealname("张三");
UserDTO userDTO = UserConverter.INSTANCE.do2dto(user);
System.out.println(userDTO.toString());
}
}
//package cn.com.glsx;
//
//import com.glsx.microservice.api.EchoCenterFeignService;
//import com.glsx.plat.core.web.R;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.SpringApplication;
//import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
//import org.springframework.cloud.client.loadbalancer.LoadBalanced;
//import org.springframework.context.annotation.Bean;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.client.RestTemplate;
//
//import javax.annotation.Resource;
//
///**
// * 测试spring cloud 服务调用方式
// */
//@EnableDiscoveryClient
//@SpringBootApplication
//public class TestApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(TestApplication.class, args);
// }
//
// @Slf4j
// @RestController
// static class TestController {
//
// @Autowired
// RestTemplate restTemplate;
//
// @Resource
// private EchoCenterFeignService echoCenterFeignService;
//
//// @Autowired
//// private WebClient.Builder webClientBuilder;
//
// @GetMapping("/test1")
// public String test1() {
// String result = restTemplate.getForObject("http://192.168.0.63:8829/glsx-rest-echo-center/echo/didi", String.class);
// return "Return : " + result;
// }
//
//// @GetMapping("/test")
//// public Mono<String> test() {
//// Mono<String> result = webClientBuilder.build()
//// .get()
//// .uri("http://alibaba-nacos-discovery-server/hello?name=didi")
//// .retrieve()
//// .bodyToMono(String.class);
//// return result;
//// }
//
// @GetMapping("/test3")
// public R test3() {
// String result = echoCenterFeignService.echo("this is a test!");
// return R.ok().data(result);
// }
// }
//
// @Bean
// @LoadBalanced
// public RestTemplate restTemplate() {
// return new RestTemplate();
// }
//
//// @Bean
//// @LoadBalanced
//// public WebClient.Builder loadBalancedWebClientBuilder() {
//// return WebClient.builder();
//// }
//
//}
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>rest-framework-admin</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath/>
</parent>
<artifactId>glsx-rest-admin-archetype</artifactId>
<version>1.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<description>Microservice Scaffolding project for Spring Boot</description>
<modules>
<module>glsx-rest-admin</module>
<module>glsx-rest-admin-api</module>
<module>glsx-rest-admin-dao</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring-cloud.version>Hoxton.SR6</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
<!-- <repo.internal.snapshots.url>https://repo1.maven.org/maven2</repo.internal.snapshots.url>-->
<!-- <repo.internal.releases.url>https://repo1.maven.org/maven2</repo.internal.releases.url>-->
<!-- <repo.proxy.url>https://repo1.maven.org/maven2</repo.proxy.url>-->
<!-- <repo.external.url>https://repo1.maven.org/maven2</repo.external.url>-->
</properties>
<dependencies>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-archetype-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>Local Nexus Releases Repository</name>
<url>http://192.168.3.233/nexus/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>Local Nexus Snapshots Repository</name>
<url>http://192.168.3.233/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-admin-auth</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-rest-authentication-client</artifactId>
<packaging>jar</packaging>
<name>glsx-rest-authentication-client</name>
<description>Demo Oauth2 project for Spring Cloud Oauth2 Authentication Client</description>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- feign -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--oauth2认证-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
</dependencies>
</project>
package com.springboot.cloud.auth.client.provider;
import com.glsx.plat.core.web.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
@Component
@FeignClient(name = "authentication-server")
public interface AuthProvider {
/**
* 调用签权服务,判断用户是否有权限
*
* @param authentication
* @param url
* @param method
* @return <pre>
* Result:
* {
* code:"200"
* mesg:"请求成功"
* data: true/false
* }
* </pre>
*/
@PostMapping(value = "/auth/permission")
R auth(@RequestHeader(HttpHeaders.AUTHORIZATION) String authentication, @RequestParam("url") String url, @RequestParam("method") String method);
}
package com.springboot.cloud.auth.client.service;
import com.glsx.plat.core.web.R;
import org.springframework.security.jwt.Jwt;
public interface IAuthService {
/**
* 调用签权服务,判断用户是否有权限
*
* @param authentication
* @param url
* @param method
* @return Result
*/
R authenticate(String authentication, String url, String method);
/**
* 判断url是否在忽略的范围内
* 只要是配置中的开头,即返回true
*
* @param url
* @return
*/
boolean ignoreAuthentication(String url);
/**
* 查看签权服务器返回结果,有权限返回true
*
* @param authResult
* @return
*/
boolean hasPermission(R authResult);
/**
* 是否无效authentication
*
* @param authentication
* @return
*/
boolean invalidJwtAccessToken(String authentication);
/**
* 调用签权服务,判断用户是否有权限
*
* @param authentication
* @param url
* @param method
* @return true/false
*/
boolean hasPermission(String authentication, String url, String method);
/**
* 从认证信息中提取jwt token 对象
*
* @param authentication 认证信息 Authorization: bearer header.payload.signature
* @return Jwt对象
*/
Jwt getJwt(String authentication);
}
package com.springboot.cloud.auth.client.service.impl;
import com.glsx.plat.core.web.R;
import com.springboot.cloud.auth.client.provider.AuthProvider;
import com.springboot.cloud.auth.client.service.IAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.InvalidSignatureException;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.stream.Stream;
@Slf4j
@Service
public class AuthService implements IAuthService {
@Autowired
private AuthProvider authProvider;
/**
* Authorization认证开头是"bearer "
*/
private static final int BEARER_BEGIN_INDEX = 7;
/**
* jwt token 密钥,主要用于token解析,签名验证
*/
@Value("${spring.security.oauth2.jwt.signingKey}")
private String signingKey;
/**
* 不需要网关签权的url配置(/oauth,/open)
* 默认/oauth开头是不需要的
*/
@Value("${gate.ignore.authentication.startWith}")
private String ignoreUrls = "/oauth";
/**
* jwt验签
*/
private MacSigner verifier;
@Override
public R authenticate(String authentication, String url, String method) {
return authProvider.auth(authentication, url, method);
}
@Override
public boolean ignoreAuthentication(String url) {
return Stream.of(this.ignoreUrls.split(",")).anyMatch(ignoreUrl -> url.startsWith(StringUtils.trim(ignoreUrl)));
}
@Override
public boolean hasPermission(R authResult) {
return authResult.isSuccess() && (boolean) authResult.getData();
}
@Override
public boolean hasPermission(String authentication, String url, String method) {
//token是否有效
if (invalidJwtAccessToken(authentication)) {
return Boolean.FALSE;
}
//从认证服务获取是否有权限
return hasPermission(authenticate(authentication, url, method));
}
@Override
public boolean invalidJwtAccessToken(String authentication) {
verifier = Optional.ofNullable(verifier).orElse(new MacSigner(signingKey));
//是否无效true表示无效
boolean invalid = Boolean.TRUE;
try {
Jwt jwt = getJwt(authentication);
jwt.verifySignature(verifier);
invalid = Boolean.FALSE;
} catch (InvalidSignatureException | IllegalArgumentException ex) {
log.warn("user token has expired or signature error ");
}
return invalid;
}
@Override
public Jwt getJwt(String authentication) {
return JwtHelper.decode(StringUtils.substring(authentication, BEARER_BEGIN_INDEX));
}
}
spring:
security:
oauth2:
jwt:
signingKey: 123456
gate:
ignore:
authentication:
startWith: /oauth,/open
\ No newline at end of file \ No newline at end of file
package com.springboot.cloud.auth.client.service.impl;
import com.glsx.plat.core.web.R;
import com.springboot.cloud.auth.client.provider.AuthProvider;
import com.springboot.cloud.auth.client.service.IAuthService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Field;
import static org.mockito.Mockito.when;
public class AuthServiceTest {
@InjectMocks
IAuthService authService;
@Mock
AuthProvider authProvider;
private static final String VALID_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ6aG91dGFvbyIsInNjb3BlIjpbInJlYWQiXSwib3JnYW5pemF0aW9uIjoiemhvdXRhb28iLCJleHAiOjE1Mjc0NTM5NDQsImF1dGhvcml0aWVzIjpbIkFETUlOIiwiSVQiXSwianRpIjoiZTZiNzM5ZmUtYWEzZC00Y2RmLWIxZjUtNzZkMmVlMjU0ODU1IiwiY2xpZW50X2lkIjoidGVzdF9jbGllbnQifQ.l6PQrs98zT40H6Ad4NHE7NSXyeWnMn-ZhURw3zO-EfE";
private static final String BEARER = "bearer ";
@Before
public void before() throws NoSuchFieldException, IllegalAccessException {
authService = new AuthService();
setInstancePrivateField(authService, "signingKey", "123456");
setInstancePrivateField(authService, "ignoreUrls", "/oauth,/open");
MockitoAnnotations.initMocks(this);
}
private void setInstancePrivateField(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
Field signingKeyField = instance.getClass().getDeclaredField(fieldName);
signingKeyField.setAccessible(true);
signingKeyField.set(instance, value);
}
@Test
public void testInvalidJwtAccessToken_假如授权服务通过给定密钥生成了token_当输入该token组成的authentication_那么返回false表示token有效() {
Assert.assertFalse(authService.invalidJwtAccessToken(BEARER + VALID_TOKEN));
}
@Test
public void testInvalidJwtAccessToken_假如有一正常的token_当输入没有bearer开头的authentication_那么返回true表示token无效() {
Assert.assertTrue(authService.invalidJwtAccessToken(VALID_TOKEN));
}
@Test
public void testInvalidJwtAccessToken_假如_当输入随机字串_那么返回true表示token无效() {
String authentication = BEARER + "im random string";
Assert.assertTrue(authService.invalidJwtAccessToken(authentication));
}
@Test
public void testInvalidJwtAccessToken_假如有人获取用户token_当输入篡改过playload中信息_那么返回true表示token无效() {
String authentication = BEARER + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.111eyJGc2VyX25hbWUiOiJ6aG91dGFvbyIsInNjb3BlIjpbInJlYWQiXSwib3JnYW5pemF0aW9uIjoiemhvdXRhb28iLCJleHAiOjE1Mjc0NTM5NDQsImF1dGhvcml0aWVzIjpbIkFETUlOIiwiSVQiXSwianRpIjoiZTZiNzM5ZmUtYWEzZC00Y2RmLWIxZjUtNzZkMmVlMjU0ODU1IiwiY2xpZW50X2lkIjoidGVzdF9jbGllbnQifQ.l6PQrs98zT40H6Ad4NHE7NSXyeWnMn-ZhURw3zO-EfE";
Assert.assertTrue(authService.invalidJwtAccessToken(authentication));
}
@Test
public void testInvalidJwtAccessToken_假如有人获取用户token_当输入token去掉了signature_那么返回true表示token无效() {
String authentication = BEARER + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ6aG91dGFvbyIsInNjb3BlIjpbInJlYWQiXSwib3JnYW5pemF0aW9uIjoiemhvdXRhb28iLCJleHAiOjE1Mjc0NTM5NDQsImF1dGhvcml0aWVzIjpbIkFETUlOIiwiSVQiXSwianRpIjoiZTZiNzM5ZmUtYWEzZC00Y2RmLWIxZjUtNzZkMmVlMjU0ODU1IiwiY2xpZW50X2lkIjoidGVzdF9jbGllbnQifQ";
Assert.assertTrue(authService.invalidJwtAccessToken(authentication));
}
@Test
public void testAuthenticate_假如用户authentication正确且有对请求url有权限_当用户请求该url_那么返回成功有权限() {
when(authProvider.auth(BEARER + VALID_TOKEN, "/users", "POST")).thenReturn(R.ok().data(true));
Assert.assertTrue((Boolean) authService.authenticate(BEARER + VALID_TOKEN, "/users", "POST").getData());
}
@Test
public void testAuthenticate_假如用户authentication正确且有对请求url只有POST权限_当用户请求该url的GET_那么返回成功无权限() {
when(authProvider.auth(BEARER + VALID_TOKEN, "/users", "GET")).thenReturn(R.ok().data(false));
Assert.assertFalse((Boolean) authService.authenticate(BEARER + VALID_TOKEN, "/users", "GET").getData());
}
@Test
public void testHasPermission_假如_当传入无效token_那么返回无权限() {
Assert.assertFalse(authService.hasPermission("invalid token", "/users", "POST"));
}
@Test
public void testHasPermission_假如用户authentication正确且有对请求url有权限_当用户请求该url_那么返回成功有权限() {
when(authProvider.auth(BEARER + VALID_TOKEN, "/users", "POST")).thenReturn(R.ok().data(true));
Assert.assertTrue(authService.hasPermission(BEARER + VALID_TOKEN, "/users", "POST"));
}
@Test
public void testHasPermission_假如用户authentication正确且有对请求url只有POST权限_当用户请求该url的GET_那么返回成功无权限() {
when(authProvider.auth(BEARER + VALID_TOKEN, "/users", "GET")).thenReturn(R.ok().data(false));
Assert.assertFalse(authService.hasPermission(BEARER + VALID_TOKEN, "/users", "GET"));
}
@Test
public void testIgnoreAuthentication_假如配置的忽略前缀为oauth和open_当用户请求以oauth开头的url_那么返回返回true() {
Assert.assertTrue(authService.ignoreAuthentication("/oauth/token?test=123"));
}
@Test
public void testIgnoreAuthentication_假如配置的忽略前缀为oauth和open_当用户请求以open开头的url_那么返回返回true() {
Assert.assertTrue(authService.ignoreAuthentication("/open/"));
}
@Test
public void testIgnoreAuthentication_假如配置的忽略前缀为oauth和open_当用户请求以test开头的url_那么返回返回true() {
Assert.assertFalse(authService.ignoreAuthentication("/test"));
}
@Test
public void testIgnoreAuthentication_假如配置的忽略前缀为oauth和open_当用户请求以open结尾的url_那么返回返回true() {
Assert.assertFalse(authService.ignoreAuthentication("/test/open"));
}
}
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-admin-auth</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-rest-authentication-server</artifactId>
<packaging>war</packaging>
<name>glsx-rest-authentication-server</name>
<description>Demo Oauth2 project for Spring Cloud Oauth2 Authentication Server</description>
<properties>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- spring security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.2.1.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
</dependency>
</dependencies>
</project>
package com.springboot.auth.authentication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class Oauth2AuthenticationApplication {
public static void main(String[] args) {
SpringApplication.run(Oauth2AuthenticationApplication.class, args);
}
}
package com.springboot.auth.authentication.config;
import com.springboot.auth.authentication.entity.Resource;
import com.springboot.auth.authentication.service.IResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Created by zhoutaoo on 2018/5/25.
*/
@Component
@Slf4j
class LoadResourceDefine {
@Autowired
private IResourceService resourceService;
@Autowired
private HandlerMappingIntrospector mvcHandlerMappingIntrospector;
@Bean
public Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes() {
Set<Resource> resources = resourceService.findAll();
Map<RequestMatcher, ConfigAttribute> map = resources.stream()
.collect(Collectors.toMap(
resource -> {
MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(mvcHandlerMappingIntrospector, resource.getUrl());
mvcRequestMatcher.setMethod(HttpMethod.resolve(resource.getMethod()));
return mvcRequestMatcher;
},
resource -> new SecurityConfig(resource.getCode())
)
);
log.debug("resourceConfigAttributes:{}", map);
return map;
}
}
package com.springboot.auth.authentication.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Value("${spring.security.oauth2.jwt.signingKey}")
private String signingKey;
@Override
public void configure(ResourceServerSecurityConfigurer resourceServerSecurityConfigurer) throws Exception {
resourceServerSecurityConfigurer
.tokenStore(tokenStore())
.resourceId("WEBS");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(signingKey);
return converter;
}
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authentication.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@Slf4j
public class WebServerSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
log.debug("HttpSecurity configure method");
http.csrf().disable();
http.authorizeRequests()
.anyRequest().authenticated();
}
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authentication.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Table;
@Data
@NoArgsConstructor
@Entity
@Table(name = "d_resource")
public class Resource extends BaseEntity {
private String code;
private String name;
private String type;
private String url;
private String method;
private String description;
}
package com.springboot.auth.authentication.mapper;
import com.springboot.auth.authentication.entity.Resource;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.Set;
@Mapper
@Repository
public interface ResourceMapper {
@Select("SELECT id,code,type,name,url,method,description,created_time,updated_time,created_by,updated_by" +
" FROM resources")
Set<Resource> findAll();
@Select("<script>" +
"SELECT DISTINCT rs.code,rs.url,rs.name,rs.type,rs.method,rs.description" +
" FROM roles r" +
" INNER JOIN roles_resources_relation rrr ON r.id = rrr.role_id" +
" INNER JOIN resources rs ON rs.id = rrr.resource_id" +
" WHERE r.code IN " +
" <foreach collection='roleCodes' item='roleCode' index='index' open='(' close=')' separator=',' >" +
" #{roleCode}" +
" </foreach>" +
"</script>")
Set<Resource> queryByRoleCodes(@Param("roleCodes") String[] roleCodes);
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authentication.rest;
import com.glsx.plat.core.web.R;
import com.springboot.auth.authentication.service.IAuthenticationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@Slf4j
public class AuthenticationController {
@Autowired
IAuthenticationService authenticationService;
@RequestMapping(method = RequestMethod.POST, value = "/auth/permission")
public R decide(@RequestParam String url, @RequestParam String method, HttpServletRequest request) {
boolean decide = authenticationService.decide(new HttpServletRequestAuthWrapper(request, url, method));
return R.ok().data(decide);
}
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authentication.rest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Created by zhoutaoo on 2018/5/26.
*/
public class HttpServletRequestAuthWrapper extends HttpServletRequestWrapper {
private String url;
private String method;
/**
* @param url
* @param method
*/
public HttpServletRequestAuthWrapper(HttpServletRequest request, String url, String method) {
super(request);
this.url = url;
this.method = method;
}
@Override
public String getMethod() {
return this.method;
}
@Override
public String getServletPath() {
return this.url;
}
}
package com.springboot.auth.authentication.service;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
@Service
public interface IAuthenticationService {
/**
* 校验权限
*
* @param authRequest
* @return 是否有权限
*/
boolean decide(HttpServletRequest authRequest);
}
package com.springboot.auth.authentication.service;
import com.springboot.auth.authentication.entity.Resource;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public interface IResourceService {
/**
* 返回所有的资源定义内容,resources表中
*
* @return
*/
Set<Resource> findAll();
/**
* 根据角色code查询到角色把对应的资源定义
*
* @param roleCodes
* @return
*/
Set<Resource> queryByRoleCodes(String[] roleCodes);
}
package com.springboot.auth.authentication.service.impl;
import com.springboot.auth.authentication.entity.Resource;
import com.springboot.auth.authentication.service.IAuthenticationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@Slf4j
public class AuthenticationService implements IAuthenticationService {
/**
* 未在资源库中的URL默认标识
*/
public static final String NONEXISTENT_URL = "NONEXISTENT_URL";
@Autowired
private ResourceService resourceService;
/**
* 系统中所有权限集合
*/
Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes;
/**
* 从数据库中加载注入
*
* @param resourceConfigAttributes
*/
@Autowired
public AuthenticationService(Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes) {
this.resourceConfigAttributes = resourceConfigAttributes;
}
/**
* @param authRequest 访问的url,method
* @return 有权限true, 无权限或全局资源中未找到请求url返回否
*/
@Override
public boolean decide(HttpServletRequest authRequest) {
log.debug("正在访问的url是:{},method:{}", authRequest.getServletPath(), authRequest.getMethod());
//获取用户认证信息
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//获取此url,method访问对应的权限资源信息
ConfigAttribute urlConfigAttribute = findConfigAttributesByUrl(authRequest);
if (NONEXISTENT_URL.equals(urlConfigAttribute.getAttribute()))
log.debug("url未在资源池中找到,拒绝访问");
//获取此访问用户所有角色拥有的权限资源
Set<Resource> userResources = findResourcesByAuthorityRoles(authentication.getAuthorities());
//用户拥有权限资源 与 url要求的资源进行对比
return isMatch(urlConfigAttribute, userResources);
}
/**
* url对应资源与用户拥有资源进行匹配
*
* @param urlConfigAttribute
* @param userResources
* @return
*/
public boolean isMatch(ConfigAttribute urlConfigAttribute, Set<Resource> userResources) {
return userResources.stream().anyMatch(resource -> resource.getCode().equals(urlConfigAttribute.getAttribute()));
}
/**
* 根据url和method查询到对应的权限信息
*
* @param authRequest
* @return
*/
public ConfigAttribute findConfigAttributesByUrl(HttpServletRequest authRequest) {
return this.resourceConfigAttributes.keySet().stream()
.filter(requestMatcher -> requestMatcher.matches(authRequest))
.map(requestMatcher -> this.resourceConfigAttributes.get(requestMatcher))
.peek(urlConfigAttribute -> log.debug("url在资源池中配置:{}", urlConfigAttribute.getAttribute()))
.findFirst()
.orElse(new SecurityConfig(NONEXISTENT_URL));
}
/**
* 根据用户所被授予的角色,查询到用户所拥有的资源
*
* @param authorityRoles
* @return
*/
private Set<Resource> findResourcesByAuthorityRoles(Collection<? extends GrantedAuthority> authorityRoles) {
//用户被授予的角色
log.debug("用户的授权角色集合信息为:{}", authorityRoles);
String[] authorityRoleCodes = authorityRoles.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList())
.toArray(new String[authorityRoles.size()]);
Set<Resource> resources = resourceService.queryByRoleCodes(authorityRoleCodes);
if (log.isDebugEnabled()) {
log.debug("用户被授予角色的资源数量是:{}, 资源集合信息为:{}", resources.size(), resources);
}
return resources;
}
}
package com.springboot.auth.authentication.service.impl;
import com.springboot.auth.authentication.mapper.ResourceMapper;
import com.springboot.auth.authentication.entity.Resource;
import com.springboot.auth.authentication.service.IResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class ResourceService implements IResourceService {
@Autowired
private ResourceMapper resourceMapper;
@Override
public Set<Resource> findAll() {
return resourceMapper.findAll();
}
@Override
public Set<Resource> queryByRoleCodes(String[] roleCodes) {
return resourceMapper.queryByRoleCodes(roleCodes);
}
}
server:
port: 8001
eureka:
client:
serviceUrl:
defaultZone: http://${EUREKA_ZONE_HOST:localhost}:${EUREKA_ZONE_PORT:8081}/eureka/
spring:
application:
name: authentication-server
datasource:
url: jdbc:postgresql://${POSTGRES_HOST:localhost}:${POSTGRES_PORT:5432}/spring_cloud
username: ${POSTGRES_USERNAME:postgres}
password: ${POSTGRES_PASSWORD:postgres}
driver-class-name: org.postgresql.Driver
security:
oauth2:
jwt:
signingKey: 123456
package com.springboot.auth.authentication;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import java.util.List;
import java.util.stream.Collectors;
public class ApplicationTests {
@Test
public void testMethod() {
List<SimpleGrantedAuthority> authorities;
SimpleGrantedAuthority admin = new SimpleGrantedAuthority("ADMIN");
SimpleGrantedAuthority user = new SimpleGrantedAuthority("USER");
authorities = Lists.newArrayList(admin, user);
authorities.stream().map(authority -> authority.getAuthority()).collect(Collectors.toList());
}
@Test
public void testMatcher() {
MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}");
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("GET", "/users/1")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("GET", "/users/aaa")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("GET", "/users")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("POST", "/users/1")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("PUT", "/users/1")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("DELETE", "/users/1")));
}
}
package com.springboot.auth.authentication.mapper;
import com.springboot.auth.authentication.entity.Resource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Set;
import static org.hamcrest.Matchers.greaterThan;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ResourceMapperTest {
@Autowired
private ResourceMapper resourceMapper;
@Test
public void testFindAll_假如已配置有资源_当获取所有时_那么可以获取到所有资源集合() {
Set<Resource> resources = resourceMapper.findAll();
Assert.assertThat(resources.size(), greaterThan(2));
}
@Test
public void testQueryByRoleCodes_假如存在角色FIN_当传入1个角色_那么可以查询到这个角色拥有的资源() {
Set<Resource> resources = resourceMapper.queryByRoleCodes(new String[]{"FIN"});
Assert.assertThat(resources.size(), greaterThan(0));
}
@Test
public void testQueryByRoleCodes_假如存在角色ADMIN和FIN_当传入这2个角色_那么可以查询到2个角色拥有的资源的并集() {
Set<Resource> resources = resourceMapper.queryByRoleCodes(new String[]{"ADMIN", "FIN"});
Assert.assertThat(resources.size(), greaterThan(2));
}
@Test
public void testQueryByRoleCodes_假如不存在角色NOTHING_当传入角色NOTHING时_那么不能查询到角色拥有的资源() {
Set<Resource> resources = resourceMapper.queryByRoleCodes(new String[]{"NOTHING"});
Assert.assertEquals(0, resources.size());
}
@Test
public void testQueryByRoleCodes_假如存在角色ADMIN且不存在角色NOTHING_当传入ADMIN时_那么可以查询到存在的角色拥有的资源() {
Set<Resource> resources = resourceMapper.queryByRoleCodes(new String[]{"ADMIN", "NOTHING"});
Assert.assertThat(resources.size(), greaterThan(2));
}
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authentication.service.impl;
import com.google.common.collect.Sets;
import com.springboot.auth.authentication.entity.Resource;
import com.springboot.auth.authentication.rest.HttpServletRequestAuthWrapper;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by zhoutaoo on 2018/5/26.
*/
public class AuthenticationServiceTest {
private Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes = new HashMap() {
{
MvcRequestMatcher mvcRequestMatcher1 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users");
mvcRequestMatcher1.setMethod(HttpMethod.resolve("POST"));
MvcRequestMatcher mvcRequestMatcher2 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}");
mvcRequestMatcher2.setMethod(HttpMethod.resolve("PUT"));
MvcRequestMatcher mvcRequestMatcher3 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}");
mvcRequestMatcher3.setMethod(HttpMethod.resolve("DELETE"));
MvcRequestMatcher mvcRequestMatcher4 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}");
mvcRequestMatcher4.setMethod(HttpMethod.resolve("GET"));
MvcRequestMatcher mvcRequestMatcher5 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}/order");
mvcRequestMatcher5.setMethod(HttpMethod.resolve("GET"));
put(mvcRequestMatcher1, new SecurityConfig("user_manager:btn_add"));
put(mvcRequestMatcher2, new SecurityConfig("user_manager:btn_edit"));
put(mvcRequestMatcher3, new SecurityConfig("user_manager:btn_del"));
put(mvcRequestMatcher4, new SecurityConfig("user_manager:view"));
put(mvcRequestMatcher5, new SecurityConfig("user_order:view"));
}
};
@Test
public void testGetConfigAttributesByUrl_假如存在如上资源信息_当请求不存在method的资源时_那么返回NONEXISTENT_URL() {
AuthenticationService authenticationService = new AuthenticationService(this.resourceConfigAttributes);
ConfigAttribute attributesByUrl = authenticationService
.findConfigAttributesByUrl(new HttpServletRequestAuthWrapper(new MockHttpServletRequest(), "/users/1/order", "POST"));
Assert.assertEquals("NONEXISTENT_URL", attributesByUrl.getAttribute());
}
@Test
public void testGetConfigAttributesByUrl_假如存在如上资源信息_当请求url存在参数时_那么返回匹配的资源信息() {
AuthenticationService authenticationService = new AuthenticationService(this.resourceConfigAttributes);
ConfigAttribute attributesByUrl = authenticationService
.findConfigAttributesByUrl(new HttpServletRequestAuthWrapper(new MockHttpServletRequest(), "/users/1/order", "GET"));
Assert.assertEquals("user_order:view", attributesByUrl.getAttribute());
}
@Test
public void testGetConfigAttributesByUrl_假如存在如上资源信息_当请求存在的资源时_那么返回url和method都匹配的资源信息() {
AuthenticationService authenticationService = new AuthenticationService(this.resourceConfigAttributes);
ConfigAttribute attributesByUrl = authenticationService
.findConfigAttributesByUrl(new HttpServletRequestAuthWrapper(new MockHttpServletRequest(), "/users", "POST"));
Assert.assertEquals("user_manager:btn_add", attributesByUrl.getAttribute());
}
@Test
public void testIsMatch_假如存在如上资源信息_当给定包含在资源信息时_那么返回true() {
AuthenticationService authenticationService = new AuthenticationService(null);
Resource resource = new Resource();
resource.setCode("user_manager:view");
Set<Resource> resources = Sets.newHashSet(resource);
Assert.assertTrue(authenticationService.isMatch(new SecurityConfig("user_manager:view"), resources));
}
@Test
public void testIsMatch_假如存在如上资源信息_当给不包含在资源信息时_那么返回false() {
AuthenticationService authenticationService = new AuthenticationService(null);
Resource resource = new Resource();
resource.setCode("user_manager:manager");
Set<Resource> resources = Sets.newHashSet(resource);
Assert.assertFalse(authenticationService.isMatch(new SecurityConfig("user_manager:view"), resources));
}
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authentication.service.impl;
import com.springboot.auth.authentication.entity.Resource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Set;
import static org.hamcrest.Matchers.greaterThan;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ResourceServiceTest {
@Autowired
private ResourceService resourceService;
@Test
public void testFindAll_假如已配置有资源_当获取所有时_那么可以获取到所有资源集合() {
Set<Resource> resources = resourceService.findAll();
Assert.assertThat(resources.size(), greaterThan(2));
}
@Test
public void testQueryByRoleCodes_假如存在角色ADMIN_当传入ADMIN时_那么可以获取到角色拥有的资源集合() {
Set<Resource> resources = resourceService.queryByRoleCodes(new String[]{"ADMIN"});
Assert.assertThat(resources.size(), greaterThan(2));
}
@Test
public void testQueryByRoleCodes_假如不存在角色NOTHING_当传入NOTHING时_那么获取不到资源信息() {
Set<Resource> resources = resourceService.queryByRoleCodes(new String[]{"NOTHING"});
Assert.assertEquals(0, resources.size());
}
}
\ No newline at end of file \ No newline at end of file
server:
port: 9001
eureka:
client:
serviceUrl:
defaultZone: http://${EUREKA_ZONE_HOST:localhost}:${EUREKA_ZONE_PORT:8081}/eureka/
spring:
datasource:
druid:
web-stat-filter:
enabled: false
url: jdbc:h2:mem:spring_cloud;MODE=PostgreSQL;INIT=RUNSCRIPT FROM '../db/ddl/oauth2_ddl.sql'\;RUNSCRIPT FROM '../db/ddl/users_ddl.sql'\;RUNSCRIPT FROM '../db/dml/oauth2_dml.sql'\;RUNSCRIPT FROM '../db/dml/users_dml.sql'
username: sa
password:
driver-class-name: org.h2.Driver
mvc:
throw-exception-if-no-handler-found: true
servlet:
multipart:
max-request-size: "2MB"
max-file-size: "2MB"
jackson:
time-zone: GMT+8
security:
oauth2:
jwt:
signingKey: 123456
logging:
level:
org.springframework.web: info
org.apache.ibatis: info
java.sql.PreparedStatement: info
java.sql.Statement: info
Java.sql.Connection: info
path: logs/
file:
max-size: 1GB
mybatis:
configuration:
map-underscore-to-camel-case: true
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-admin-auth</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-rest-authorization-server</artifactId>
<packaging>war</packaging>
<name>glsx-rest-authorization-server</name>
<description>Demo Oauth2 project for Spring Cloud Oauth2 Authorization Server</description>
<properties>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- spring security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>
</project>
授权服务介绍
----------
## 简介
授权微服务,可供网关gateway实现微服务对外权限的授予
## 启动
部署脚本:启动数据库,部署`auth/db`下的ddl和dml脚本
启动应用:`mvn spring-boot:run`
应用地址:`http://localhost:8000`
## 使用指南
### 初始账号
本例中初使化的客户端与用户账号
client_id: `test_client`
client_secret: `test_secret`
username: `admin`
password: `password`
### JWT Token介绍
本例中access_token Payload 负载(中间部分)base64解码后结构如下
```
{
"user_name": "admin", //用户username,users表中username字段
"scope": [
"read" //授权权限范围
],
"organization": "admin", //组织,该字段为自定义,自定义方法见 开发指南中
"exp": 1531975621, //过期时间
"authorities": [ //授权权限,本例子中为用户授权的角色名,roles表中code字段
"ADMIN"
],
"jti": "23408d38-8cdc-4460-beac-24c76dc7629a", //jwt token的id
"client_id": "test_client" //客户端id,oauth_client_details表中client_id
}
```
### 接口测试
#### 密码模式,grant_type=password
用途:可用于用户通过前端应用登陆、使用应用,如app,web等终端
![postman](../../docs/auth/oauth2_password_token.png)
请求报文
```
POST /oauth/token?scope=read&grant_type=password HTTP/1.1
Host: localhost:8000
Authorization: Basic dGVzdF9jbGllbnQ6dGVzdF9zZWNyZXQ=
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
username=zhoutaoo&password=password
```
响应报文
```
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ6aG91dGFvbyIsInNjb3BlIjpbInJlYWQiXSwib3JnYW5pemF0aW9uIjoiemhvdXRhb28iLCJleHAiOjE1MzE5NzM4MTgsImF1dGhvcml0aWVzIjpbIkFETUlOIiwiSVQiXSwianRpIjoiNTFiODY4ZDEtMGNlMS00ZmI4LTkwMWQtOWM3YmZmYzBhZGJiIiwiY2xpZW50X2lkIjoidGVzdF9jbGllbnQifQ.BlIryRbSL414rDv5EfzZSjpjvWybcX3hEJy3fV8l6Wo",
"token_type": "bearer",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ6aG91dGFvbyIsInNjb3BlIjpbInJlYWQiXSwib3JnYW5pemF0aW9uIjoiemhvdXRhb28iLCJhdGkiOiI1MWI4NjhkMS0wY2UxLTRmYjgtOTAxZC05YzdiZmZjMGFkYmIiLCJleHAiOjE1MzQ1MjI2MTgsImF1dGhvcml0aWVzIjpbIkFETUlOIiwiSVQiXSwianRpIjoiMGU2N2Q5MDEtOThlMC00ZTk3LTkwNzgtODllMTBmZTRjOGI2IiwiY2xpZW50X2lkIjoidGVzdF9jbGllbnQifQ.zNtWWG8xxPsjTZKghOjyGNDjnhHqnPvikfqN1uynh3U",
"expires_in": 43199,
"scope": "read",
"organization": "zhoutaoo",
"jti": "51b868d1-0ce1-4fb8-901d-9c7bffc0adbb"
}
```
### 客户端模式,grant_type=client_credentials
用途:可用于接口开放给第三方商户,商户申请client_id和密码,即可调用授权的接口
![postman](../../docs/auth/oauth2_client_token.png)
请求报文
```
POST /oauth/token?scope=read&grant_type=client_credentials HTTP/1.1
Host: localhost:8000
Authorization: Basic dGVzdF9jbGllbnQ6dGVzdF9zZWNyZXQ=
Cache-Control: no-cache
```
响应报文
```
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIl0sIm9yZ2FuaXphdGlvbiI6InRlc3RfY2xpZW50IiwiZXhwIjoxNTMxOTczMzAzLCJqdGkiOiI0NjBlYWRkNi1iNjU3LTRkNzAtYTFjZi00MWJjYWM5OTFkNzgiLCJjbGllbnRfaWQiOiJ0ZXN0X2NsaWVudCJ9.d_7f1N81hKWakA0eQeHOqW88-mYjYGgXHChMR_S6d6w",
"token_type": "bearer",
"expires_in": 43199,
"scope": "read",
"organization": "test_client",
"jti": "460eadd6-b657-4d70-a1cf-41bcac991d78"
}
```
### 刷新access_token
用途:使用refresh_token更新access_token
![postman](../../docs/auth/oauth2_refresh_token.png)
请求报文
```
POST /oauth/token?scope=read&amp;grant_type=refresh_token&amp;refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiXSwib3JnYW5pemF0aW9uIjoiYWRtaW4iLCJhdGkiOiJlODA5MDRkYi1mMDBkLTRkNDAtOGFlNS0xMWY2OTVlMzZjMTEiLCJleHAiOjE1MzQ1MjQzMTQsImF1dGhvcml0aWVzIjpbIkFETUlOIl0sImp0aSI6Ijk0OGUxZTYxLTBkOTUtNGYzMC04YWNlLWFmNDcyNjU2ZWNiNCIsImNsaWVudF9pZCI6InRlc3RfY2xpZW50In0.XrvwAi14NTJXm029CGFD3BsPgZdYQ7u1nszYlf42Eo8 HTTP/1.1
Host: host1:8000
Authorization: Basic dGVzdF9jbGllbnQ6dGVzdF9zZWNyZXQ=
Cache-Control: no-cache
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
```
响应报文
```
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiXSwib3JnYW5pemF0aW9uIjoiYWRtaW4iLCJleHAiOjE1MzE5NzU2MjEsImF1dGhvcml0aWVzIjpbIkFETUlOIl0sImp0aSI6IjIzNDA4ZDM4LThjZGMtNDQ2MC1iZWFjLTI0Yzc2ZGM3NjI5YSIsImNsaWVudF9pZCI6InRlc3RfY2xpZW50In0.qawS1Z4j_h4vNx10GBC_Y_PHM1LLSQt64eniWLGzsJY",
"token_type": "bearer",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiXSwib3JnYW5pemF0aW9uIjoiYWRtaW4iLCJhdGkiOiIyMzQwOGQzOC04Y2RjLTQ0NjAtYmVhYy0yNGM3NmRjNzYyOWEiLCJleHAiOjE1MzQ1MjQzMTQsImF1dGhvcml0aWVzIjpbIkFETUlOIl0sImp0aSI6Ijk0OGUxZTYxLTBkOTUtNGYzMC04YWNlLWFmNDcyNjU2ZWNiNCIsImNsaWVudF9pZCI6InRlc3RfY2xpZW50In0.eHRWxFZDJDq_2RDPL4DhyMy7IwF8GHn_LQU5j7ZkF8k",
"expires_in": 43199,
"scope": "read",
"organization": "admin",
"jti": "23408d38-8cdc-4460-beac-24c76dc7629a"
}
```
### 开发指南
#### token自定义
见CustomTokenEnhancer类
```
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> additionalInfo = Maps.newHashMap();
//自定义token内容,加入组织机构信息
additionalInfo.put("organization", authentication.getName());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
```
#### jwt使用
* jwt配置
见AuthenticationServerConfig类,本例中jwt使用对称加密算法,
也可使用非对称,这里不做实现,如有需要,请自行研究。
```
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(signingKey);
return converter;
}
```
* jwt对称密钥配置项
```
spring:
security:
oauth2:
jwt:
signingKey: 123456
```
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authorization;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class Oauth2AuthorizationApplication {
public static void main(String[] args) {
SpringApplication.run(Oauth2AuthorizationApplication.class, args);
}
}
package com.springboot.auth.authorization.config;
import com.springboot.auth.authorization.config.custom.CustomTokenEnhancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import javax.sql.DataSource;
import java.util.Arrays;
@Configuration
@EnableAuthorizationServer
public class AuthenticationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Qualifier("dataSource")
@Autowired
DataSource dataSource;
@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;
/**
* jwt 对称加密密钥
*/
@Value("${spring.security.oauth2.jwt.signingKey}")
private String signingKey;
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("isAuthenticated()")
.checkTokenAccess("permitAll()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//配置客户端信息,从数据库中读取,对应oauth_client_details表
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//配置token的数据源、自定义的tokenServices等信息,配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory
endpoints.tokenStore(tokenStore())
.tokenEnhancer(tokenEnhancerChain())
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Bean
public ApprovalStore approvalStore() {
return new JdbcApprovalStore(dataSource);
}
/**
* 授权码模式持久名授权码
*
* @return
*/
@Bean
protected AuthorizationCodeServices authorizationCodeServices() {
//授权码存储等处理方式类,使用jdbc,操作oauth_code表
return new JdbcAuthorizationCodeServices(dataSource);
}
/**
* token的持久化
*
* @return
*/
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
/**
* 自定义token
*
* @return
*/
@Bean
public TokenEnhancerChain tokenEnhancerChain() {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new CustomTokenEnhancer(), accessTokenConverter()));
return tokenEnhancerChain;
}
/**
* jwt token的生成配置
*
* @return
*/
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(signingKey);
return converter;
}
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authorization.config;
import lombok.extern.slf4j.Slf4j;
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.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@Slf4j
public class WebServerSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.anyRequest().authenticated();
}
/**
* 注入自定义的userDetailsService实现,获取用户信息,设置密码加密方式
*
* @param authenticationManagerBuilder
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
/**
* 将 AuthenticationManager 注册为 bean , 方便配置 oauth server 的时候使用
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authorization.config.custom;
import com.google.common.collect.Maps;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import java.util.Map;
/**
* 自定义token携带内容
*/
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> additionalInfo = Maps.newHashMap();
//自定义token内容,加入组织机构信息
additionalInfo.put("organization", authentication.getName());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authorization.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Role extends BaseEntity {
private String code;
private String name;
private String description;
}
package com.springboot.auth.authorization.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class User extends BaseEntity {
private String name;
private String mobile;
private String username;
private String password;
private Boolean enabled;
private Boolean accountNonExpired;
private Boolean credentialsNonExpired;
private Boolean accountNonLocked;
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authorization.mapper;
import com.springboot.auth.authorization.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.Set;
@Mapper
@Repository
public interface RoleMapper {
@Select("SELECT DISTINCT r.code,r.name,r.description" +
" FROM users_roles_relation urr" +
" INNER JOIN roles r ON r.id = urr.role_id" +
" WHERE urr.user_id = #{userId}")
Set<Role> queryByUserId(long userId);
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authorization.mapper;
import com.springboot.auth.authorization.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface UserMapper {
@Select("SELECT id,username,password,enabled,account_non_expired,credentials_non_expired,account_non_locked,name,mobile,created_time,updated_time,created_by,updated_by" +
" FROM users WHERE username = #{username}")
User getByUsername(String username);
}
\ No newline at end of file \ No newline at end of file
package com.springboot.auth.authorization.service;
import com.springboot.auth.authorization.entity.Role;
import com.springboot.auth.authorization.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.stream.Collectors;
@Service("userDetailsService")
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private IUserService userService;
@Autowired
private IRoleService roleService;
@Override
public UserDetails loadUserByUsername(String username) {
User user = userService.getByUsername(username);
log.info("loadByUsername:{}", user.toString());
return new org.springframework.security.core.userdetails.User(
username,
user.getPassword(),
user.getEnabled(),
user.getAccountNonExpired(),
user.getCredentialsNonExpired(),
user.getAccountNonLocked(),
this.obtainGrantedAuthorities(user));
}
/**
* 获得登录者所有角色的权限集合.
*
* @param user
* @return
*/
private Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
Set<Role> roles = roleService.queryUserRolesByUserId(user.getId());
log.info("user:{},roles:{}", user.getUsername(), roles);
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getCode()))
.collect(Collectors.toSet());
}
}
package com.springboot.auth.authorization.service;
import com.springboot.auth.authorization.entity.Role;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public interface IRoleService {
Set<Role> queryUserRolesByUserId(long userId);
}
package com.springboot.auth.authorization.service;
import com.springboot.auth.authorization.entity.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public interface IUserService {
@Cacheable(value = "#id")
User getByUsername(String username);
}
package com.springboot.auth.authorization.service.impl;
import com.springboot.auth.authorization.mapper.RoleMapper;
import com.springboot.auth.authorization.entity.Role;
import com.springboot.auth.authorization.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class RoleService implements IRoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public Set<Role> queryUserRolesByUserId(long userId) {
return roleMapper.queryByUserId(userId);
}
}
package com.springboot.auth.authorization.service.impl;
import com.springboot.auth.authorization.mapper.UserMapper;
import com.springboot.auth.authorization.entity.User;
import com.springboot.auth.authorization.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public User getByUsername(String username) {
return userMapper.getByUsername(username);
}
}
server:
port: 8000
eureka:
client:
serviceUrl:
defaultZone: http://${EUREKA_ZONE_HOST:localhost}:${EUREKA_ZONE_PORT:8081}/eureka/
spring:
application:
name: authorization-server
rabbitmq:
host: ${RABBIT_MQ_HOST:localhost}
port: ${RABBIT_MQ_PORT:5672}
username: ${RABBIT_MQ_USERNAME:guest}
password: ${RABBIT_MQ_PASSWORD:guest}
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
##password: ${REDIS_PASSWORD:}
datasource:
url: jdbc:postgresql://${POSTGRES_HOST:localhost}:${POSTGRES_PORT:5432}/spring_cloud
username: ${POSTGRES_USERNAME:postgres}
password: ${POSTGRES_PASSWORD:postgres}
driver-class-name: org.postgresql.Driver
boot:
admin:
url: http://${BOOT_ADMIN_HOST:localhost}:${BOOT_ADMIN_PORT:8022}
zipkin:
baseUrl: http://localhost:8091
security:
oauth2:
jwt:
signingKey: 123456
logging:
level:
org.springframework.web: debug
org.springframework.security: DEBUG
com.springboot.auth: DEBUG
org.apache.ibatis: debug
java.sql.PreparedStatement: debug
path: logs/
file:
max-size: 1GB
management:
endpoints:
web:
exposure:
include: '*'
mybatis:
configuration:
map-underscore-to-camel-case: true
package com.springboot.auth.authorization;
import org.junit.Test;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
public class ApplicationTests {
@Test
public void contextLoads() {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
System.out.println(passwordEncoder.encode("test_secret"));
}
}
server:
port: 9001
eureka:
client:
serviceUrl:
defaultZone: http://${EUREKA_ZONE_HOST:localhost}:${EUREKA_ZONE_PORT:8081}/eureka/
spring:
datasource:
druid:
web-stat-filter:
enabled: false
url: jdbc:h2:mem:spring_cloud;MODE=PostgreSQL;INIT=RUNSCRIPT FROM '../db/ddl/oauth2_ddl.sql'\;RUNSCRIPT FROM '../db/ddl/users_ddl.sql'\;RUNSCRIPT FROM '../db/dml/oauth2_dml.sql'\;RUNSCRIPT FROM '../db/dml/users_dml.sql'
username: sa
password:
driver-class-name: org.h2.Driver
mvc:
throw-exception-if-no-handler-found: true
servlet:
multipart:
max-request-size: "2MB"
max-file-size: "2MB"
jackson:
time-zone: GMT+8
flyway:
locations: classpath:.
baseline-on-migrate: true
devtools:
livereload:
enabled: true
logging:
level:
org.springframework.web: info
org.apache.ibatis: info
java.sql.PreparedStatement: info
java.sql.Statement: info
Java.sql.Connection: info
path: logs/
file:
max-size: 1GB
management:
endpoints:
web:
exposure:
include: '*'
mybatis:
configuration:
map-underscore-to-camel-case: true
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>rest-framework-admin</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-rest-admin-auth</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<description>Demo Oauth2 project for Spring Cloud Oauth2</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<modules>
<module>glsx-rest-authentication-server</module>
<module>glsx-rest-authentication-client</module>
<module>glsx-rest-authorization-server</module>
</modules>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-rest-admin-demo</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-rest-seata-account-api</artifactId>
<dependencies>
<!-- feign -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.account.api;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author payu
*/
@FeignClient(name = "glsx-rest-seata-account", path = "/account")
public interface AccountFeignClient {
/**
* 扣除指定账户金额
*
* @param userId 账户编号
* @param money 金额
*/
@PostMapping("/deductByUserId")
void deduct(@RequestParam("userId") String userId, @RequestParam("money") Double money);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.account.model;
import lombok.Data;
@Data
public class AccountBO {
private Long id;
private String userId;
private Double amount;
}
package cn.com.glsx.account.model;
import lombok.Data;
@Data
public class AccountDTO {
private Long id;
private String userId;
private Double amount;
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-rest-admin-demo</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-rest-seata-account</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-seata</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-seata-account-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@Slf4j
@EnableDiscoveryClient
@SpringBootApplication
public class AccountServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
log.info("账户服务启动成功.");
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.account.modules.controller;
import cn.com.glsx.account.api.AccountFeignClient;
import cn.com.glsx.account.modules.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 账户接口实现
*
* @author payu
*/
@RestController
@RequestMapping("/account")
public class AccountFeignController implements AccountFeignClient {
/**
* 账户业务逻辑
*/
@Autowired
private AccountService accountService;
@Override
@PostMapping(value = "/deductByUserId", consumes = "application/x-www-form-urlencoded")
public void deduct(@RequestParam("userId") String userId, @RequestParam("money") Double money) {
accountService.debit(userId, money);
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.account.modules.converter;
import cn.com.glsx.account.model.AccountBO;
import cn.com.glsx.account.model.AccountDTO;
import cn.com.glsx.account.modules.entity.Account;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
/**
* 解耦dao与api的实体映射
* 字段名不一样,用@Mapping来处理
* https://github.com/mapstruct/mapstruct-examples
*
* @author payu
*/
@Mapper
public interface AccountConverter {
AccountConverter INSTANCE = Mappers.getMapper(AccountConverter.class);
AccountDTO do2dto(Account account);
Account dto2do(AccountDTO accountDTO);
AccountBO do2bo(Account account);
Account bo2do(AccountBO accountBO);
}
package cn.com.glsx.account.modules.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Data
@Table(name = "t_account")
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@Column(name = "user_id")
private String userId;
private Double amount;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.account.modules.mapper;
import cn.com.glsx.account.modules.entity.Account;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AccountMapper extends CommonBaseMapper<Account> {
Account selectByUserId(String userId);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.account.modules.service;
import cn.com.glsx.account.modules.entity.Account;
import cn.com.glsx.account.modules.mapper.AccountMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 账户业务逻辑处理
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class AccountService {
@Autowired
private AccountMapper accountMapper;
/**
* @param accountId {@link Account#getId()}
* @param money 扣除的金额
*/
public void debit(Long accountId, Double money) {
Account account = accountMapper.selectByPrimaryKey(accountId);
if (ObjectUtils.isEmpty(account)) {
throw new RuntimeException("账户:" + accountId + ",不存在.");
}
if (account.getAmount() - money < 0) {
throw new RuntimeException("账户:" + accountId + ",余额不足.");
}
account.setAmount(account.getAmount() - money);
accountMapper.updateByPrimaryKeySelective(account);
}
/**
* @param userId {@link Account#getUserId()}
* @param money 扣除的金额
*/
public void debit(String userId, Double money) {
Account account = accountMapper.selectByUserId(userId);
if (ObjectUtils.isEmpty(account)) {
throw new RuntimeException("账户:" + userId + ",不存在.");
}
if (account.getAmount() - money < 0) {
throw new RuntimeException("账户:" + userId + ",余额不足.");
}
account.setAmount(account.getAmount() - money);
accountMapper.updateByPrimaryKeySelective(account);
}
}
#项目名称
spring.application.name=glsx-rest-seata-account
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=DEV_GROUP_SEATA
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
spring.profiles.active=dev
#配置格式
spring.cloud.nacos.config.file-extension=yaml
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=DEV_GROUP_SEATA
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-rest-seata-share.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.account.modules.mapper.AccountMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.account.modules.entity.Account">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_id" jdbcType="VARCHAR" property="userId" />
<result column="amount" jdbcType="DOUBLE" property="amount" />
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, user_id, amount
</sql>
<select id="selectByUserId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_account
where user_id = #{userId}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-rest-admin-demo</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-rest-seata-business</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-seata</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-seata-storage-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-rest-seata-order-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author payu
*/
@Slf4j
@EnableFeignClients(basePackages = "cn.com.glsx.*.api")
@EnableDiscoveryClient
@SpringBootApplication
public class BusinessServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BusinessServiceApplication.class, args);
log.info("业务服务启动成功.");
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.business.modules.controller;
import cn.com.glsx.business.modules.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author payu
*/
@RestController
@RequestMapping("/business")
public class BusinessController {
@Autowired
private BusinessService businessService;
/**
* 购买下单,模拟全局事务提交
*
* @return
*/
@RequestMapping("/purchase/commit")
public Boolean purchaseCommit() {
businessService.purchase("1001", "2001", 1);
return true;
}
/**
* 购买下单,模拟全局事务回滚
*
* @return
*/
@RequestMapping("/purchase/rollback")
public Boolean purchaseRollback() {
try {
businessService.purchase("1002", "2001", 1);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
package cn.com.glsx.business.modules.service;
import cn.com.glsx.order.api.OrderFeignClient;
import cn.com.glsx.order.model.OrderBO;
import cn.com.glsx.storage.api.StorageFeignClient;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Slf4j
@Service
public class BusinessService {
@Resource
private StorageFeignClient storageFeignClient;
@Resource
private OrderFeignClient orderFeignClient;
/**
* 减库存,下订单
* 通过{@link StorageFeignClient#reduceStock(String, int)}方法减少商品的库存,判断库存剩余数量
*
* @param userId
* @param commodityCode
* @param orderCount
*/
@GlobalTransactional
public void purchase(String userId, String commodityCode, int orderCount) {
log.info("开始全局事务,XID = " + RootContext.getXID());
//1、扣减库存
storageFeignClient.reduceStock(commodityCode, orderCount);
//2、创建订单
OrderBO orderBO = new OrderBO();
orderBO.setUserId(userId);
orderBO.setCommodityCode(commodityCode);
orderBO.setOrderCount(orderCount);
orderFeignClient.submitOrder(orderBO);
}
}
#项目名称
spring.application.name=glsx-rest-seata-business
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=DEV_GROUP_SEATA
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
spring.profiles.active=dev
#配置格式
spring.cloud.nacos.config.file-extension=yaml
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=DEV_GROUP_SEATA
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-rest-seata-share.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!