当前位置:   article > 正文

demo(二)SpringBoot+dubbo+Spring Sercurity+VUE实例----(后端)_springboot+vue+dubbo

springboot+vue+dubbo

下面写个简单的token单一点登录系统来验证下。当访问系统未登录时,跳转到登录页,登录后进入首页,左侧导航栏展示默认菜单(首页)和有权限的菜单。

一、写在前面:关于session和token的使用,网上争议一直很大。总的来说争议在这里:

(1)session是空间换时间,而token是时间换空间。session占用空间,但是可以管理过期时间,token管理部了过期时间,但是不占用空间.
(2)sessionId失效问题和token内包含。
(3)session基于cookie,app请求并没有cookie 。
(4)token更加安全(每次请求都需要带上)。
 

二、效果:

前端:vue

后端:springboot+dubbo+mybatis+spring sercurity+JWT+ token单一点登录。

效果:

分别启动前后端服务,访问首页http://localhost:9528/#/index,由于未登录,跳转到登录页

登录后跳转到首页,http://localhost:9528/#/dashboard

左侧菜单栏展开,显示所有的权限:

此时在postman调用一次登录接口,再次回到浏览器刷新或者调用接口(如点击用户管理页),跳转到登录页面。证明单一点登录实现。 

三、数据库:

1、t_user:

2、t_role:

3、t_authority:

4、t_user_role:

5、t_role_authoriy:

四、后端代码:

  • api:

1、pom:

  1. <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">
  2. <modelVersion>4.0.0</modelVersion>
  3. <groupId>com.demo</groupId>
  4. <artifactId>mysercurity-api</artifactId>
  5. <version>1.0.0-SNAPSHOT</version>
  6. </project>

2、dto:

  1. public class AuthorityDTO implements Serializable {
  2. private Integer id;
  3. private String authorityName;
  4. private String authorityCode;
  5. }
  1. public class RoleDTO implements Serializable {
  2. private Integer id;
  3. private String roleCode;
  4. private String roleName;
  5. }
  1. public class UserDTO implements Serializable {
  2. private Integer id;
  3. private String userName;
  4. private String password;
  5. private String userNickName;
  6. //验证码
  7. private String code;
  8. private List<RoleDTO> roles;
  9. }
  • service:

1、pom:

  1. <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">
  2. <modelVersion>4.0.0</modelVersion>
  3. <groupId>com.demo</groupId>
  4. <artifactId>mysercurity-service</artifactId>
  5. <version>0.0.1-SNAPSHOT</version>
  6. <!-- springBoot -->
  7. <parent>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-parent</artifactId>
  10. <version>1.4.1.RELEASE</version>
  11. </parent>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-web</artifactId>
  16. </dependency>
  17. <!-- api -->
  18. <dependency>
  19. <groupId>com.demo</groupId>
  20. <artifactId>mysercurity-api</artifactId>
  21. <version>1.0.0-SNAPSHOT</version>
  22. </dependency>
  23. <!-- mybatis -->
  24. <dependency>
  25. <groupId>org.mybatis.spring.boot</groupId>
  26. <artifactId>mybatis-spring-boot-starter</artifactId>
  27. <version>1.1.1</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>mysql</groupId>
  31. <artifactId>mysql-connector-java</artifactId>
  32. <version>5.1.21</version>
  33. </dependency>
  34. <!-- dubbo -->
  35. <dependency>
  36. <groupId>com.alibaba.spring.boot</groupId>
  37. <artifactId>dubbo-spring-boot-starter</artifactId>
  38. <version>2.0.0</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>commons-collections</groupId>
  42. <artifactId>commons-collections</artifactId>
  43. <version>3.2.1</version>
  44. </dependency>
  45. <dependency>
  46. <groupId>commons-lang</groupId>
  47. <artifactId>commons-lang</artifactId>
  48. <version>2.5</version>
  49. </dependency>
  50. <!--zk-->
  51. <dependency>
  52. <groupId>com.github.sgroschupf</groupId>
  53. <artifactId>zkclient</artifactId>
  54. <version>0.1</version>
  55. <exclusions>
  56. <exclusion>
  57. <artifactId>log4j</artifactId>
  58. <groupId>log4j</groupId>
  59. </exclusion>
  60. <exclusion>
  61. <artifactId>slf4j-log4j12</artifactId>
  62. <groupId>org.slf4j</groupId>
  63. </exclusion>
  64. </exclusions>
  65. </dependency>
  66. </dependencies>
  67. </project>

2、application.properties:

  1. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
  3. spring.datasource.username=root
  4. spring.datasource.password=wtyy
  5. mybatis.mapper-locations=classpath*:Mapper/*Mapper.xml
  6. server.port=9998

 3、provider.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://code.alibabatech.com/schema/dubbo
  7. http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
  8. <dubbo:application name="mysercurity-service"/>
  9. <dubbo:provider timeout="3000" retries="0"/>
  10. <!-- register改为false不注册到注册中心 -->
  11. <dubbo:registry protocol="zookeeper" address="192.168.57.xxx:2181,192.168.57.xx:2181,192.168.59.xxx:2181"
  12. register="false" check="false"/>
  13. <dubbo:protocol name="dubbo" port="20881"/>
  14. <dubbo:service interface="com.demo.service.UserService" ref="userService"></dubbo:service>
  15. <dubbo:service interface="com.demo.service.RoleService" ref="roleService"></dubbo:service>
  16. </beans>

4、serviceImpl:

  1. package com.demo.service.impl;
  2. import com.demo.dao.UserRoleDao;
  3. import com.demo.dto.RoleDTO;
  4. import com.demo.service.RoleService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.util.List;
  8. @Service("roleService")
  9. public class RoleServiceImpl implements RoleService {
  10. @Autowired
  11. private UserRoleDao userRoleDao;
  12. @Override
  13. public List<RoleDTO> findRoleByUserId(Integer id) {
  14. return userRoleDao.findRoleByUserId(id);
  15. }
  16. }
  1. package com.demo.service.impl;
  2. import com.demo.dao.AuthorityDao;
  3. import com.demo.dao.UserDao;
  4. import com.demo.dao.UserRoleDao;
  5. import com.demo.dto.AuthorityDTO;
  6. import com.demo.dto.RoleDTO;
  7. import com.demo.dto.UserDTO;
  8. import com.demo.exception.UsernameNotFoundException;
  9. import com.demo.service.RoleService;
  10. import com.demo.service.UserService;
  11. import org.apache.commons.collections.CollectionUtils;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.stereotype.Service;
  14. import java.util.ArrayList;
  15. import java.util.Collections;
  16. import java.util.List;
  17. import java.util.stream.Collectors;
  18. @Service("userService")
  19. public class UserServiceImpl implements UserService {
  20. @Autowired
  21. private UserDao userDao;
  22. @Autowired
  23. private UserRoleDao userRoleDao;
  24. @Autowired
  25. private AuthorityDao authorityDao;
  26. @Autowired
  27. private RoleService roleService;
  28. @Override
  29. public UserDTO findByUserName(String username) {
  30. UserDTO user = userDao.findByUserName(username);
  31. if(user == null){
  32. throw new UsernameNotFoundException("用户不存在");
  33. }
  34. List<RoleDTO> roles = roleService.findRoleByUserId(user.getId());
  35. user.setRoles(roles);
  36. return user;
  37. }
  38. @Override
  39. public List<UserDTO> getAllUsers() {
  40. return userDao.getAllUsers();
  41. }
  42. @Override
  43. public List<AuthorityDTO> getAuthortiesByUserId(Integer userId) {
  44. List<RoleDTO> roles = userRoleDao.findRoleByUserId(userId);
  45. if(CollectionUtils.isNotEmpty(roles)){
  46. List<Integer> roleIds = roles.stream().map(RoleDTO::getId).collect(Collectors.toList());
  47. return authorityDao.getAuthortiesByRoleIds(roleIds);
  48. }
  49. return new ArrayList<>();
  50. }
  51. }

 5、dao:

  1. public interface AuthorityDao {
  2. List<AuthorityDTO> getAuthortiesByRoleIds(@Param("roleIds") List<Integer> roleIds);
  3. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.demo.dao.AuthorityDao">
  4. <select id="getAuthortiesByRoleIds" resultType="com.demo.dto.AuthorityDTO">
  5. select
  6. a.id id,
  7. a.authority_code authorityCode,
  8. a.authority_name authorityName
  9. from t_role_authoriy ra left join t_authority a on ra.authority_id = a.id
  10. where ra.role_id in
  11. <foreach collection="roleIds" item="item" open="(" close=")" separator=",">
  12. #{item}
  13. </foreach>
  14. and ra.is_delete = 0
  15. </select>
  16. </mapper>
  1. public interface UserDao {
  2. public UserDTO findByUserName(@Param("userName") String userAccount);
  3. List<UserDTO> getAllUsers();
  4. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.demo.dao.UserDao">
  4. <select id="findByUserName" resultType="com.demo.dto.UserDTO">
  5. select
  6. id,
  7. user_nick_name userNickName,
  8. user_name userName,
  9. user_nick_name userNickName,
  10. user_password password
  11. from t_user where user_name = #{userName}
  12. and is_delete = 0
  13. </select>
  14. <select id="getAllUsers" resultType="com.demo.dto.UserDTO">
  15. select
  16. id,
  17. user_nick_name userNickName,
  18. user_name userName,
  19. user_nick_name userNickName
  20. from t_user
  21. </select>
  22. </mapper>
  1. public interface UserRoleDao {
  2. List<RoleDTO> findRoleByUserId(@Param("userId") Integer userId);
  3. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.demo.dao.UserRoleDao">
  4. <select id="findRoleByUserId" resultType="com.demo.dto.RoleDTO">
  5. select
  6. r.id id,
  7. r.role_code roleCode,
  8. r.role_name roleName
  9. from t_user_role ur
  10. left join t_role r
  11. on ur.role_id = r.id
  12. where ur.user_id = #{userId}
  13. and is_delete = 0
  14. </select>
  15. </mapper>

6、启动类:

  1. package com.demo;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.context.annotation.ImportResource;
  6. @SpringBootApplication
  7. @MapperScan("com.demo.dao")
  8. @ImportResource("classpath:provider.xml")
  9. public class ServiceStart {
  10. public static void main(String args[]){
  11. SpringApplication.run(ServiceStart.class,args);
  12. }
  13. }
  • rest:

1、pom:

  1. <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">
  2. <modelVersion>4.0.0</modelVersion>
  3. <groupId>com.demo</groupId>
  4. <artifactId>mysercurity-rest</artifactId>
  5. <version>0.0.1-SNAPSHOT</version>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>1.4.1.RELEASE</version>
  10. </parent>
  11. <dependencies>
  12. <!--api-->
  13. <dependency>
  14. <groupId>com.demo</groupId>
  15. <artifactId>mysercurity-api</artifactId>
  16. <version>1.0.0-SNAPSHOT</version>
  17. </dependency>
  18. <!-- dubbo -->
  19. <dependency>
  20. <groupId>com.alibaba.spring.boot</groupId>
  21. <artifactId>dubbo-spring-boot-starter</artifactId>
  22. <version>2.0.0</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-security</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>io.jsonwebtoken</groupId>
  34. <artifactId>jjwt</artifactId>
  35. <version>0.9.0</version>
  36. </dependency>
  37. <!-- redis -->
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-data-redis</artifactId>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework.session</groupId>
  44. <artifactId>spring-session-data-redis</artifactId>
  45. </dependency>
  46. <dependency>
  47. <groupId>redis.clients</groupId>
  48. <artifactId>jedis</artifactId>
  49. </dependency>
  50. <!--httpclient -->
  51. <dependency>
  52. <groupId>org.apache.httpcomponents</groupId>
  53. <artifactId>httpclient</artifactId>
  54. <version>4.5.6</version>
  55. </dependency>
  56. <dependency>
  57. <groupId>com.alibaba</groupId>
  58. <artifactId>fastjson</artifactId>
  59. <version>1.2.31</version>
  60. </dependency>
  61. <dependency>
  62. <groupId>commons-collections</groupId>
  63. <artifactId>commons-collections</artifactId>
  64. <version>3.2.1</version>
  65. </dependency>
  66. <dependency>
  67. <groupId>commons-lang</groupId>
  68. <artifactId>commons-lang</artifactId>
  69. <version>2.5</version>
  70. </dependency>
  71. <!--zk-->
  72. <dependency>
  73. <groupId>com.github.sgroschupf</groupId>
  74. <artifactId>zkclient</artifactId>
  75. <version>0.1</version>
  76. <exclusions>
  77. <exclusion>
  78. <artifactId>log4j</artifactId>
  79. <groupId>log4j</groupId>
  80. </exclusion>
  81. <exclusion>
  82. <artifactId>slf4j-log4j12</artifactId>
  83. <groupId>org.slf4j</groupId>
  84. </exclusion>
  85. </exclusions>
  86. </dependency>
  87. </dependencies>
  88. </project>

2、配置文件:

(1)application.properties:

  1. server.port=9999
  2. server.context-path=/demo
  3. spring.redis.host=localhost
  4. spring.redis.port=6379
  5. #spring.redis.password=
  6. spring.redis.database=1
  7. spring.redis.pool.max-active=8
  8. spring.redis.pool.max-wait=-1
  9. spring.redis.pool.max-idle=500
  10. spring.redis.pool.min-idle=0
  11. spring.redis.timeout=0

(2) consumer.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
  6. <dubbo:application name="mysercurity-test" />
  7. <dubbo:consumer timeout="3000" retries="0" check="false"/>
  8. <dubbo:registry protocol="zookeeper" address="192.168.57.xxx:2181,192.168.57.xx:2181,192.168.59.xxx:2181" register="true" timeout="100000"/>
  9. <!-- 加上 url="dubbo://127.0.0.1:20881" 表示直连本地-->
  10. <dubbo:reference interface="com.demo.service.UserService" id="userService"
  11. url="dubbo://127.0.0.1:20881"/>
  12. <dubbo:reference interface="com.demo.service.RoleService" id="roleService"
  13. url="dubbo://127.0.0.1:20881"/>
  14. </beans>

 3、config:

  1. package com.demo.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  5. @Configuration
  6. public class WebMvcConfig extends WebMvcConfigurerAdapter {
  7. @Override
  8. public void addCorsMappings(CorsRegistry registry) {
  9. registry.addMapping("/**").allowedHeaders("*")
  10. .allowedMethods("*")
  11. .allowedOrigins("*")
  12. .allowCredentials(true);
  13. }
  14. }

 4、常量:

(1)CommonEnums:

  1. package com.demo.constants;
  2. public enum CommonEnums {
  3. CODE_200(200,"请求成功"),
  4. CODE_300(300,"登录成功"),
  5. CODE_301(301,"登录失败"),
  6. CODE_302(302,"退出成功"),
  7. CODE_303(303,"退出失败"),
  8. CODE_304(304,"用户或密码错误"),
  9. CODE_305(305,"账户已被锁定"),
  10. CODE_401(401,"授权失败"),
  11. CODE_400(400,"业务异常"),
  12. CODE_402(402,"非法请求"),
  13. CODE_403(403,"验证码错误"),
  14. CODE_405(405,"验证码无效"),
  15. CODE_500(500,"系统异常"),
  16. ;
  17. public final int code;
  18. public final String message;
  19. CommonEnums(int code, String message ) {
  20. this.code = code;
  21. this.message = message;
  22. }
  23. public int getCode() {
  24. return this.code;
  25. }
  26. public String getMessage() {
  27. return message;
  28. }
  29. public static String getEnumToValue(int code){
  30. for (CommonEnums statusEnum: CommonEnums.values()) {
  31. if (statusEnum.code == code){
  32. return statusEnum.message;
  33. }
  34. }
  35. return "";
  36. }
  37. }

 (2)Constants :

  1. package com.demo.constants;
  2. public class Constants {
  3. public static final long EXPIRATIONTIME = (long)1000 * 60 * 60 * 24 * 1; //1 days
  4. public static final String SECRET = "spring-security-jwt";
  5. public static final String HEADER_STRING = "token";
  6. public static final String TOKEN_PREFIX = "Bearer";
  7. public static final String TOKEN_JWT="token_jwt:";
  8. public static final String JWT_USER="jwt_user:";
  9. public static final String LOCK="lock:";
  10. public static final String ERROR_NUM="error_num:";
  11. }

 5、dto:

(1)JWTUserDTO:

  1. package com.demo.dto;
  2. import org.springframework.security.core.GrantedAuthority;
  3. import org.springframework.security.core.userdetails.UserDetails;
  4. import java.util.ArrayList;
  5. import java.util.Collection;
  6. import java.util.List;
  7. /**
  8. * 登录用户
  9. */
  10. public class JWTUserDTO implements UserDetails {
  11. private Integer id;
  12. private String userName;
  13. private String password;
  14. private String userNickName;
  15. private List<RoleDTO> roles = new ArrayList<>();
  16. private Collection<? extends GrantedAuthority> authorities;
  17. public JWTUserDTO(){
  18. }
  19. public JWTUserDTO(Integer id, String userName, String password, String userNickName,
  20. Collection<? extends GrantedAuthority> authorities, List<RoleDTO> roles){
  21. this.id = id;
  22. this.userName = userName;
  23. this.userNickName = userNickName;
  24. this.password = password;
  25. this.authorities = authorities;
  26. this.roles = roles;
  27. }
  28. @Override
  29. public String getUsername() {
  30. return userName;
  31. }
  32. @Override
  33. public boolean isAccountNonExpired() {
  34. return false;
  35. }
  36. @Override
  37. public boolean isAccountNonLocked() {
  38. return false;
  39. }
  40. @Override
  41. public boolean isCredentialsNonExpired() {
  42. return false;
  43. }
  44. @Override
  45. public boolean isEnabled() {
  46. return false;
  47. }
  48. public void setUsername(String username) {
  49. this.userName = username;
  50. }
  51. @Override
  52. public Collection<? extends GrantedAuthority> getAuthorities() {
  53. return authorities;
  54. }
  55. @Override
  56. public String getPassword() {
  57. return password;
  58. }
  59. public Integer getId() {
  60. return id;
  61. }
  62. public void setId(Integer id) {
  63. this.id = id;
  64. }
  65. public void setPassword(String password) {
  66. this.password = password;
  67. }
  68. public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
  69. this.authorities = authorities;
  70. }
  71. public List<RoleDTO> getRoles() {
  72. return roles;
  73. }
  74. public void setRoles(List<RoleDTO> roles) {
  75. this.roles = roles;
  76. }
  77. public String getUserName() {
  78. return userName;
  79. }
  80. public void setUserName(String userName) {
  81. this.userName = userName;
  82. }
  83. public String getUserNickName() {
  84. return userNickName;
  85. }
  86. public void setUserNickName(String userNickName) {
  87. this.userNickName = userNickName;
  88. }
  89. }

(2)ResponseMessage:

  1. package com.demo.dto;
  2. import com.demo.constants.CommonEnums;
  3. public class ResponseMessage {
  4. private int code;
  5. private String status;
  6. private String message;
  7. private String errorMessage;
  8. private String errorExceptionMessage;
  9. private Object data;
  10. public ResponseMessage(int code,String status,Object data){
  11. this.code = code;
  12. this.status = status;
  13. this.data = data;
  14. }
  15. public ResponseMessage(int code,String status,String message){
  16. this.code = code;
  17. this.status = status;
  18. this.message = message;
  19. }
  20. public ResponseMessage(int code,String status,String message,Object data){
  21. this.code = code;
  22. this.status = status;
  23. this.message = message;
  24. this.data = data;
  25. }
  26. public ResponseMessage(int code,String status,String message,String errorMessage){
  27. this.code = code;
  28. this.status = status;
  29. this.message = message;
  30. this.errorMessage = errorMessage;
  31. }
  32. public ResponseMessage(int code,String status,String message,String errorMessage,String errorExceptionMessage){
  33. this.code = code;
  34. this.status = status;
  35. this.message = message;
  36. this.errorMessage = errorMessage;
  37. this.errorExceptionMessage = errorExceptionMessage;
  38. }
  39. public static ResponseMessage success(String message){
  40. return new ResponseMessage(CommonEnums.CODE_200.code,"success",message);
  41. }
  42. public static ResponseMessage success(Object data){
  43. return new ResponseMessage(CommonEnums.CODE_200.code,"success",data);
  44. }
  45. public static ResponseMessage success(String message,Object data){
  46. return new ResponseMessage(CommonEnums.CODE_200.code,"success",message,data);
  47. }
  48. public static ResponseMessage success(int code,String message,Object data){
  49. return new ResponseMessage(code,"success",message,data);
  50. }
  51. public static ResponseMessage success(){
  52. return new ResponseMessage(CommonEnums.CODE_200.code,null,CommonEnums.CODE_200.message);
  53. }
  54. public static ResponseMessage success(int code,Object data){
  55. return new ResponseMessage(code,"success",data);
  56. }
  57. public static ResponseMessage success(int code,String message){
  58. return new ResponseMessage(code,"success",message);
  59. }
  60. public static ResponseMessage error(int code,String message){
  61. return new ResponseMessage(code,"error",message);
  62. }
  63. public static ResponseMessage error(int code,String message,String errorMessage){
  64. return new ResponseMessage(code,"error",message,errorMessage);
  65. }
  66. public static ResponseMessage error(int code,String message,String errorMessage,String errorExceptionMessage){
  67. return new ResponseMessage(code,"error",message,errorMessage,errorExceptionMessage);
  68. }
  69. public static ResponseMessage error(String message,String errorMessage){
  70. return new ResponseMessage(CommonEnums.CODE_500.code,"error",message,errorMessage);
  71. }
  72. public static ResponseMessage error(String message){
  73. return new ResponseMessage(CommonEnums.CODE_400.code,"error",message);
  74. }
  75. public static ResponseMessage infor(int code,String message){
  76. return new ResponseMessage(code,"infor",message);
  77. }
  78. public String getStatus() {
  79. return status;
  80. }
  81. public void setStatus(String status) {
  82. this.status = status;
  83. }
  84. public String getMessage() {
  85. return message;
  86. }
  87. public void setMessage(String message) {
  88. this.message = message;
  89. }
  90. public Object getData() {
  91. return data;
  92. }
  93. public void setData(Object data) {
  94. this.data = data;
  95. }
  96. public String getErrorMessage() {
  97. return errorMessage;
  98. }
  99. public void setErrorMessage(String errorMessage) {
  100. this.errorMessage = errorMessage;
  101. }
  102. public String getErrorExceptionMessage() {
  103. return errorExceptionMessage;
  104. }
  105. public void setErrorExceptionMessage(String errorExceptionMessage) {
  106. this.errorExceptionMessage = errorExceptionMessage;
  107. }
  108. public int getCode() {
  109. return code;
  110. }
  111. public void setCode(int code) {
  112. this.code = code;
  113. }
  114. }

6、exception:

(1):

  1. package com.demo.exception;
  2. import com.alibaba.fastjson.JSON;
  3. import com.demo.constants.CommonEnums;
  4. import com.demo.dto.ResponseMessage;
  5. import org.apache.http.entity.ContentType;
  6. import org.springframework.security.core.AuthenticationException;
  7. import org.springframework.security.web.authentication.AuthenticationFailureHandler;
  8. import org.springframework.stereotype.Component;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.IOException;
  13. @Component
  14. public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
  15. @Override
  16. public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
  17. HttpServletResponse httpServletResponse, AuthenticationException e)
  18. throws IOException, ServletException {
  19. httpServletResponse.setContentType(ContentType.APPLICATION_JSON.toString());
  20. httpServletResponse.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_304.code,CommonEnums.CODE_304.message)));
  21. }
  22. }

 (2):

  1. package com.demo.exception;
  2. import com.alibaba.fastjson.JSON;
  3. import com.demo.constants.CommonEnums;
  4. import com.demo.dto.ResponseMessage;
  5. import org.apache.http.entity.ContentType;
  6. import org.springframework.security.core.AuthenticationException;
  7. import org.springframework.security.web.AuthenticationEntryPoint;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.IOException;
  12. public class Http401AuthenticationEntryPoint implements AuthenticationEntryPoint {
  13. @Override
  14. public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
  15. response.setContentType(ContentType.APPLICATION_JSON.toString());
  16. response.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_401.code,CommonEnums.CODE_401.message)));
  17. }
  18. }

(3):

  1. package com.demo.exception;
  2. public class TokenException extends RuntimeException {
  3. private static final long serialVersionUID = 1L;
  4. public TokenException(String message) {
  5. super(message);
  6. }
  7. }

 7、factory:主要是全局上下文:

(1):

  1. package com.demo.factory;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.BeansException;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.ApplicationContextAware;
  7. import org.springframework.stereotype.Component;
  8. @Component
  9. public class ApplicationContextRegister implements ApplicationContextAware {
  10. private static Logger logger = LoggerFactory.getLogger(ApplicationContextRegister.class);
  11. private static ApplicationContext APPLICATION_CONTEXT;
  12. /**
  13. * 设置spring上下文
  14. * @param applicationContext spring上下文
  15. * @throws BeansException
  16. * */
  17. @Override
  18. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  19. logger.debug("ApplicationContext registed-->{}", applicationContext);
  20. DefaultBeanFactory.setSpringApplicationContext(applicationContext);
  21. APPLICATION_CONTEXT = applicationContext;
  22. }
  23. /**
  24. * 获取容器
  25. * @return
  26. */
  27. public static ApplicationContext getApplicationContext() {
  28. return APPLICATION_CONTEXT;
  29. }
  30. /**
  31. * 获取容器对象
  32. * @param type
  33. * @param <T>
  34. * @return
  35. */
  36. public static <T> T getBean(Class<T> type) {
  37. return APPLICATION_CONTEXT.getBean(type);
  38. }
  39. }

(2):

  1. package com.demo.factory;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class DefaultBeanFactory {
  5. private static ApplicationContext context = null;
  6. private static DefaultBeanFactory instance = null;
  7. private static Object lock = new Object();
  8. private DefaultBeanFactory(String filepath){
  9. try {
  10. context = new ClassPathXmlApplicationContext(filepath);
  11. } catch (Exception e) {
  12. }
  13. }
  14. @SuppressWarnings("static-access")
  15. private DefaultBeanFactory(ApplicationContext context){
  16. try {
  17. this.context = context;
  18. } catch (Exception e) {
  19. }
  20. }
  21. public static void setSpringApplicationContext(ApplicationContext context){
  22. synchronized (lock) {
  23. instance = new DefaultBeanFactory(context);
  24. }
  25. }
  26. public static DefaultBeanFactory getInstance() {
  27. if(instance == null || context == null){
  28. throw new RuntimeException("Spring context is null!");
  29. }
  30. return instance;
  31. }
  32. public static DefaultBeanFactory getInstance(String filepath) {
  33. synchronized (lock) {
  34. instance = new DefaultBeanFactory(filepath);
  35. }
  36. return instance;
  37. }
  38. public Object getBean(String name) {
  39. return context.getBean(name);
  40. }
  41. }

(3):

  1. package com.demo.factory;
  2. import com.demo.util.RedisClient;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. public class ServiceFactory {
  6. private static Logger logger = LoggerFactory.getLogger(ServiceFactory.class);
  7. private static ServiceFactory instance = new ServiceFactory();
  8. private final String REDIS_CLIENT_BEAN="redisClient";
  9. private final String USER_ACTION_LOG_SERVICE = "userActionLogService";
  10. public ServiceFactory() {
  11. // TODO Auto-generated constructor stub
  12. }
  13. public static ServiceFactory getInstance() {
  14. if (instance == null) {
  15. instance = new ServiceFactory();
  16. }
  17. return instance;
  18. }
  19. public RedisClient createRedisClient() {
  20. try {
  21. return (RedisClient) DefaultBeanFactory.getInstance().getBean(REDIS_CLIENT_BEAN);
  22. } catch (Exception e) {
  23. throw new RuntimeException("创建 createRedisClient BEAN 异常", e);
  24. }
  25. }
  26. }

8、filter:

(1):

  1. package com.demo.filter;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.demo.constants.CommonEnums;
  5. import com.demo.constants.Constants;
  6. import com.demo.dto.JWTUserDTO;
  7. import com.demo.dto.ResponseMessage;
  8. import com.demo.dto.UserDTO;
  9. import com.demo.factory.ServiceFactory;
  10. import com.demo.service.UserService;
  11. import com.demo.util.JwtProvider;
  12. import com.demo.util.RedisClient;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import org.springframework.http.HttpStatus;
  16. import org.springframework.security.authentication.AuthenticationManager;
  17. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  18. import org.springframework.security.core.context.SecurityContextHolder;
  19. import org.springframework.security.core.userdetails.UserDetails;
  20. import org.springframework.security.core.userdetails.UserDetailsService;
  21. import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
  22. import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
  23. import org.springframework.util.StringUtils;
  24. import javax.servlet.FilterChain;
  25. import javax.servlet.ServletException;
  26. import javax.servlet.http.HttpServletRequest;
  27. import javax.servlet.http.HttpServletResponse;
  28. import java.io.IOException;
  29. import java.util.Objects;
  30. import org.apache.http.entity.ContentType;
  31. /**非登录接口拦截
  32. *
  33. * 自定义JWT认证过滤器
  34. * 该类继承自BasicAuthenticationFilter,在doFilterInternal方法中,
  35. * 从http头的Authorization 项读取token数据,然后用Jwts包提供的方法校验token的合法性。
  36. * 如果校验通过,就认为这是一个取得授权的合法请求
  37. */
  38. public class JWTAuthenticationFilter extends BasicAuthenticationFilter{
  39. private static final Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
  40. private static RedisClient redisClient;
  41. static {
  42. redisClient = ServiceFactory.getInstance().createRedisClient();
  43. }
  44. private UserService userService;
  45. public JWTAuthenticationFilter(AuthenticationManager authenticationManager,
  46. UserService userService) {
  47. super(authenticationManager);
  48. this.userService = userService;
  49. }
  50. @Override
  51. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
  52. String token = request.getHeader(Constants.HEADER_STRING);
  53. String username = JwtProvider.getAuthentication(request);
  54. if(StringUtils.isEmpty(username)){
  55. response.sendError(HttpStatus.UNAUTHORIZED.value(), "Authentication Failed: username not found");
  56. return;
  57. }
  58. //效验token是否过期
  59. String tokenReids = redisClient.get(Constants.TOKEN_JWT+username);
  60. if (StringUtils.isEmpty(tokenReids)){
  61. logger.error("Token已过期: {} ",token);
  62. response.setContentType(ContentType.APPLICATION_JSON.toString());
  63. response.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_401.code,"Token已过期")));
  64. return;
  65. }
  66. if (!Objects.equals(tokenReids,token)){
  67. logger.error("Token不匹配: {} " + tokenReids);
  68. response.setContentType(ContentType.APPLICATION_JSON.toString());
  69. response.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_401.code,"Token不匹配")));
  70. return;
  71. }
  72. // if(SecurityContextHolder.getContext().getAuthentication() == null) {
  73. String userJson = redisClient.get(Constants.JWT_USER+username);
  74. UserDetails userDetails = null;
  75. if (!StringUtils.isEmpty(userJson)){
  76. JWTUserDTO jwtUser = JSONObject.parseObject(userJson,JWTUserDTO.class);
  77. userDetails = jwtUser;
  78. }else{
  79. UserDTO user = userService.findByUserName(username);
  80. userDetails = new JWTUserDTO(user.getId(),user.getUserName(),user.getPassword(),
  81. user.getUserNickName(),null,user.getRoles());
  82. redisClient.set(Constants.JWT_USER+username, JSONObject.toJSONString(userDetails));
  83. }
  84. UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
  85. authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
  86. SecurityContextHolder.getContext().setAuthentication(authentication);
  87. // }
  88. chain.doFilter(request, response);
  89. }
  90. }

(2):

  1. package com.demo.filter;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.demo.constants.CommonEnums;
  5. import com.demo.constants.Constants;
  6. import com.demo.dto.JWTUserDTO;
  7. import com.demo.dto.ResponseMessage;
  8. import com.demo.dto.UserDTO;
  9. import com.demo.exception.CustomAuthenticationFailureHandler;
  10. import com.demo.factory.ServiceFactory;
  11. import com.demo.service.UserService;
  12. import com.demo.util.JwtProvider;
  13. import com.demo.util.RedisClient;
  14. import com.fasterxml.jackson.databind.ObjectMapper;
  15. import org.apache.commons.lang.StringUtils;
  16. import org.apache.http.entity.ContentType;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.security.authentication.AuthenticationManager;
  20. import org.springframework.security.authentication.BadCredentialsException;
  21. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  22. import org.springframework.security.core.Authentication;
  23. import org.springframework.security.core.AuthenticationException;
  24. import org.springframework.security.core.userdetails.UserDetails;
  25. import org.springframework.security.core.userdetails.UserDetailsService;
  26. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  27. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  28. import javax.servlet.FilterChain;
  29. import javax.servlet.ServletException;
  30. import javax.servlet.http.HttpServletRequest;
  31. import javax.servlet.http.HttpServletResponse;
  32. import javax.servlet.http.HttpSession;
  33. import java.io.IOException;
  34. import java.util.ArrayList;
  35. import java.util.Objects;
  36. /**登录接口(/login)拦截
  37. *
  38. * 验证用户名密码正确后,生成一个token,并将token返回给客户端
  39. * 该类继承自UsernamePasswordAuthenticationFilter,重写了其中的2个方法
  40. * attemptAuthentication :接收并解析用户凭证。
  41. * successfulAuthentication :用户成功登录后,这个方法会被调用,我们在这个方法里生成token。
  42. */
  43. public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter{
  44. private static Logger logger = LoggerFactory.getLogger(JWTLoginFilter.class);
  45. private AuthenticationManager authenticationManager;
  46. private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
  47. private UserService userService;
  48. private static RedisClient redisClient;
  49. static {
  50. redisClient = ServiceFactory.getInstance().createRedisClient();
  51. }
  52. public JWTLoginFilter(AuthenticationManager authenticationManager,
  53. CustomAuthenticationFailureHandler customAuthenticationFailureHandler,
  54. UserService userService) {
  55. this.authenticationManager = authenticationManager;
  56. this.customAuthenticationFailureHandler = customAuthenticationFailureHandler;
  57. this.userService = userService;
  58. setAuthenticationManager(authenticationManager);
  59. }
  60. // 接收并解析用户凭证
  61. @Override
  62. public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
  63. String userName = "";
  64. HttpSession httpSession = req.getSession();
  65. try {
  66. UserDTO user = new ObjectMapper().readValue(req.getInputStream(), UserDTO.class);
  67. //判断用户是否多次登录失败被锁定
  68. String lock = redisClient.get(Constants.LOCK+user.getUserName());
  69. if (StringUtils.isNotEmpty(lock)) {
  70. httpSession.setAttribute("code",null);
  71. Long time = redisClient.ttl(Constants.LOCK+user.getUserName());
  72. res.setContentType(ContentType.APPLICATION_JSON.toString());
  73. res.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_305.code, CommonEnums.CODE_305.message+":"+time+"秒后解锁")));
  74. return null;
  75. }
  76. //校验验证码
  77. if (StringUtils.isNotEmpty(user.getCode())){
  78. if (!Objects.equals(user.getCode(),"1111")){
  79. String code = (String) httpSession.getAttribute("code");
  80. if(StringUtils.isEmpty(code)){
  81. httpSession.setAttribute("code",null);
  82. res.setContentType(ContentType.APPLICATION_JSON.toString());
  83. res.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_405.code,CommonEnums.CODE_405.message)));
  84. return null;
  85. }
  86. if (!Objects.equals(user.getCode().toLowerCase(),code.toLowerCase())){
  87. httpSession.setAttribute("code",null);
  88. res.setContentType(ContentType.APPLICATION_JSON.toString());
  89. res.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_403.code,CommonEnums.CODE_403.message)));
  90. return null;
  91. }
  92. }
  93. }else{
  94. httpSession.setAttribute("code",null);
  95. res.setContentType(ContentType.APPLICATION_JSON.toString());
  96. res.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_405.code,CommonEnums.CODE_405.message)));
  97. }
  98. userName = user.getUserName();
  99. return authenticationManager.authenticate(
  100. new UsernamePasswordAuthenticationToken(
  101. user.getUserName(),
  102. user.getPassword(),
  103. new ArrayList<>())
  104. );
  105. }catch (IOException e) {
  106. throw new RuntimeException(e);
  107. }catch (UsernameNotFoundException | BadCredentialsException e){
  108. try {
  109. if (StringUtils.isNotEmpty(userName)){
  110. String errorNum = redisClient.get(Constants.ERROR_NUM+userName);
  111. if (StringUtils.isNotEmpty(errorNum)){
  112. if (Objects.equals(errorNum,"3")){
  113. httpSession.setAttribute("code",null);
  114. redisClient.set(Constants.LOCK+userName,"true",120);
  115. res.setContentType(ContentType.APPLICATION_JSON.toString());
  116. res.getWriter().write(JSON.toJSONString(ResponseMessage.error(CommonEnums.CODE_305.code,CommonEnums.CODE_305.message+":120秒后解锁")));
  117. }else{
  118. httpSession.setAttribute("code",null);
  119. redisClient.set(Constants.ERROR_NUM+userName,String.valueOf(Integer.valueOf(errorNum)+1),120);
  120. customAuthenticationFailureHandler.onAuthenticationFailure(req,res,e);
  121. }
  122. }else{
  123. httpSession.setAttribute("code",null);
  124. redisClient.set(Constants.ERROR_NUM+userName,"1",120);
  125. customAuthenticationFailureHandler.onAuthenticationFailure(req,res,e);
  126. }
  127. }else{
  128. httpSession.setAttribute("code",null);
  129. customAuthenticationFailureHandler.onAuthenticationFailure(req,res,e);
  130. }
  131. } catch (Exception e1) {
  132. throw new RuntimeException(e);
  133. }
  134. return null;
  135. }
  136. }
  137. // 用户成功登录后,这个方法会被调用,我们在这个方法里生成token
  138. @Override
  139. protected void successfulAuthentication(HttpServletRequest request,
  140. HttpServletResponse response,
  141. FilterChain chain,
  142. Authentication auth) throws IOException, ServletException {
  143. HttpSession httpSession = request.getSession();
  144. httpSession.setAttribute("code",null);
  145. redisClient.del(Constants.LOCK+auth.getName());
  146. redisClient.del(Constants.ERROR_NUM+auth.getName());
  147. String token = JwtProvider.addAuthentication(response, auth.getName());
  148. UserDTO userDTO = userService.findByUserName(auth.getName());
  149. JWTUserDTO userDetails = new JWTUserDTO(userDTO.getId(),userDTO.getUserName(),userDTO.getPassword(),
  150. userDTO.getUserNickName(),null,userDTO.getRoles());;
  151. redisClient.set(Constants.JWT_USER+auth.getName(), JSONObject.toJSONString(userDetails));
  152. response.setContentType(ContentType.APPLICATION_JSON.toString());
  153. response.getWriter().write(JSON.toJSONString(ResponseMessage.success(CommonEnums.CODE_300.code,CommonEnums.CODE_300.message,token)));
  154. }
  155. }

9、rest接口:

(1) :

  1. package com.demo.rest;
  2. import com.demo.dto.ResponseMessage;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import javax.servlet.http.HttpSession;
  11. import java.util.Random;
  12. @RestController
  13. @RequestMapping("/code")
  14. public class CodeController {
  15. private static Logger logger = LoggerFactory.getLogger(CodeController.class);
  16. /**
  17. * 获取验证码
  18. */
  19. @GetMapping(value = "/getCode")
  20. public ResponseMessage images(HttpServletRequest request, HttpServletResponse response) {
  21. try {
  22. HttpSession httpSession = request.getSession();
  23. Random r = new Random();
  24. String code = String.valueOf(r.nextInt(100));
  25. httpSession.setAttribute("code",code);
  26. return ResponseMessage.success("验证码",code);
  27. } catch (Exception e) {
  28. logger.error("ValidateCodeController images ERROR MESSAGE={}", e.getMessage(), e);
  29. }
  30. return ResponseMessage.error("");
  31. }
  32. }

(2):

  1. package com.demo.rest;
  2. import com.demo.constants.CommonEnums;
  3. import com.demo.constants.Constants;
  4. import com.demo.dto.AuthorityDTO;
  5. import com.demo.dto.JWTUserDTO;
  6. import com.demo.dto.ResponseMessage;
  7. import com.demo.dto.UserDTO;
  8. import com.demo.service.UserService;
  9. import com.demo.util.RedisClient;
  10. import org.apache.commons.lang.StringUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.security.core.context.SecurityContextHolder;
  13. import org.springframework.web.bind.annotation.GetMapping;
  14. import org.springframework.web.bind.annotation.RequestMapping;
  15. import org.springframework.web.bind.annotation.RestController;
  16. import java.util.List;
  17. @RequestMapping("/user")
  18. @RestController
  19. public class UserController {
  20. @Autowired
  21. private UserService userService;
  22. @Autowired
  23. private RedisClient redisClient;
  24. /**
  25. * 获取所有用户
  26. * @return
  27. */
  28. @RequestMapping("/getAllUsers")
  29. public ResponseMessage getAllUsers(){
  30. List<UserDTO> users = userService.getAllUsers();
  31. return ResponseMessage.success(users);
  32. }
  33. /**
  34. * 获取权限
  35. */
  36. @RequestMapping("/getMyAuthorities")
  37. public ResponseMessage getMyAuthorities(){
  38. JWTUserDTO jwtUser = (JWTUserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  39. Integer currentUserId = jwtUser.getId();
  40. List<AuthorityDTO> authorityDTOS= userService.getAuthortiesByUserId(currentUserId);
  41. return ResponseMessage.success(authorityDTOS);
  42. }
  43. @GetMapping(value = "/logout")
  44. public ResponseMessage logout(HttpServletRequest request) {
  45. try{
  46. JWTUserDTO jwtUser = (JWTUserDTO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  47. String userName = jwtUser.getUsername();
  48. if (StringUtils.isEmpty(userName)){
  49. throw new RuntimeException(CommonEnums.CODE_303.message);
  50. }
  51. redisClient.del(Constants.TOKEN_JWT+userName);
  52. request.logout();
  53. }catch (Exception e){
  54. }
  55. return ResponseMessage.success(CommonEnums.CODE_200.code,CommonEnums.CODE_200.message);
  56. }
  57. }

10、sercurity:

  1. package com.demo.sercurity;
  2. import com.demo.exception.CustomAuthenticationFailureHandler;
  3. import com.demo.exception.Http401AuthenticationEntryPoint;
  4. import com.demo.filter.JWTAuthenticationFilter;
  5. import com.demo.filter.JWTLoginFilter;
  6. import com.demo.service.CustomAuthenticationProvider;
  7. import com.demo.service.UserService;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  11. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  12. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  13. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  14. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  15. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  16. import org.springframework.security.config.http.SessionCreationPolicy;
  17. import org.springframework.security.core.userdetails.UserDetailsService;
  18. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  19. /**
  20. * SpringSecurity的配置
  21. * 通过SpringSecurity的配置,将JWTLoginFilter,JWTAuthenticationFilter组合在一起
  22. */
  23. @Configuration
  24. @EnableWebSecurity
  25. @EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
  26. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  27. /**白名单
  28. * 需要放行的URL
  29. */
  30. private static final String[] AUTH_WHITELIST = {
  31. "/v2/api-docs",
  32. "/swagger-resources",
  33. "/swagger-resources/**",
  34. "/configuration/ui",
  35. "/configuration/security",
  36. "/swagger-ui.html",
  37. "/static",
  38. "/static/diagram-viewer",
  39. "/static/**",
  40. "/index.html",
  41. "/code/**", //验证码
  42. };
  43. @Autowired
  44. private UserService userService;
  45. @Autowired
  46. private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
  47. // 设置 HTTP 验证规则
  48. @Override
  49. protected void configure(HttpSecurity httpSecurity) throws Exception {
  50. httpSecurity.cors().and().csrf().disable()
  51. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
  52. .authorizeRequests()
  53. .anyRequest().authenticated() // 所有请求需要身份认证
  54. .and()
  55. .exceptionHandling()
  56. .authenticationEntryPoint(
  57. new Http401AuthenticationEntryPoint())
  58. .and()
  59. .addFilterBefore(new JWTLoginFilter(authenticationManager(),customAuthenticationFailureHandler,userService), UsernamePasswordAuthenticationFilter.class)
  60. .addFilterBefore(new JWTAuthenticationFilter(authenticationManager(),userService), UsernamePasswordAuthenticationFilter.class);
  61. //因为是spring整合了spring Security,本例加了session共享,每次检查原session的时候如果不存在的话,就会创建新的session,故需要手动设置
  62. httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
  63. }
  64. // 该方法是登录的时候会进入
  65. @Override
  66. public void configure(AuthenticationManagerBuilder auth) throws Exception {
  67. // 使用自定义身份验证组件
  68. auth.authenticationProvider(new CustomAuthenticationProvider(userService));
  69. }
  70. @Override
  71. public void configure(WebSecurity web) throws Exception {
  72. web.ignoring().antMatchers(AUTH_WHITELIST);
  73. }
  74. }

11、 service:

  1. package com.demo.service;
  2. import com.demo.dto.JWTUserDTO;
  3. import com.demo.dto.UserDTO;
  4. import com.demo.util.AESUtils;
  5. import com.demo.util.MD5Util;
  6. import org.springframework.security.authentication.AuthenticationProvider;
  7. import org.springframework.security.authentication.BadCredentialsException;
  8. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  9. import org.springframework.security.core.Authentication;
  10. import org.springframework.security.core.AuthenticationException;
  11. import org.springframework.security.core.userdetails.UserDetails;
  12. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  13. import java.security.NoSuchAlgorithmException;
  14. import java.util.Objects;
  15. /**
  16. * 自定义身份认证验证组件
  17. */
  18. public class CustomAuthenticationProvider implements AuthenticationProvider {
  19. private UserService userService;
  20. public CustomAuthenticationProvider(
  21. UserService userService
  22. ){
  23. this.userService = userService;
  24. }
  25. @Override
  26. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  27. // 获取认证的用户名 & 密码
  28. //前端带入的username
  29. String username = authentication.getName();
  30. //前端带入的加密password
  31. String passwordRsa = authentication.getCredentials().toString();
  32. //passwordRsa解密后的密码
  33. String password = "";
  34. String passwordMd5 = "";
  35. //RSA解密
  36. try {
  37. password = AESUtils.decryptStr(passwordRsa,AESUtils.key);
  38. } catch (Exception e) {
  39. throw new UsernameNotFoundException("用户不存在");
  40. }
  41. UserDTO userDO = userService.findByUserName(username);
  42. if (userDO == null) {
  43. throw new UsernameNotFoundException("用户不存在");
  44. }
  45. //判断密码
  46. try {
  47. //md5加密
  48. passwordMd5 = MD5Util.MD5(password);
  49. } catch (NoSuchAlgorithmException e) {
  50. throw new UsernameNotFoundException("用户不存在");
  51. }
  52. if (!Objects.equals(passwordMd5,userDO.getPassword())){
  53. throw new BadCredentialsException("密码错误");
  54. }
  55. UserDTO userDTO = userService.findByUserName(username);
  56. JWTUserDTO userDetails = new JWTUserDTO(userDTO.getId(),userDTO.getUserName(),userDTO.getPassword(),
  57. userDTO.getUserNickName(),null,userDTO.getRoles());
  58. // 这里设置权限和角色
  59. Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
  60. return auth;
  61. }
  62. /**
  63. * 是否可以提供输入类型的认证服务
  64. * @param authentication
  65. * @return
  66. */
  67. @Override
  68. public boolean supports(Class<?> authentication) {
  69. return authentication.equals(UsernamePasswordAuthenticationToken.class);
  70. }
  71. }

12、util:

(1):

  1. package com.demo.util;
  2. import javax.crypto.*;
  3. import javax.crypto.spec.IvParameterSpec;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import java.io.UnsupportedEncodingException;
  6. import java.nio.charset.Charset;
  7. import java.security.InvalidAlgorithmParameterException;
  8. import java.security.InvalidKeyException;
  9. import java.security.NoSuchAlgorithmException;
  10. public class AESUtils {
  11. private static String iv = "HGty&6%4ojyUyhgy";//偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
  12. private static String Algorithm = "AES";
  13. private static String AlgorithmProvider = "AES/CBC/PKCS5Padding"; //算法/模式/补码方式
  14. public final static String key="FUjs@17654HGJKKn";
  15. public static byte[] generatorKey() throws NoSuchAlgorithmException {
  16. KeyGenerator keyGenerator = KeyGenerator.getInstance(Algorithm);
  17. keyGenerator.init(256);//默认128,获得无政策权限后可为192256
  18. SecretKey secretKey = keyGenerator.generateKey();
  19. return secretKey.getEncoded();
  20. }
  21. public static IvParameterSpec getIv() throws UnsupportedEncodingException {
  22. IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
  23. System.out.println("偏移量:"+byteToHexString(ivParameterSpec.getIV()));
  24. return ivParameterSpec;
  25. }
  26. public static byte[] encrypt(String src, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException,
  27. InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
  28. SecretKey secretKey = new SecretKeySpec(key, Algorithm);
  29. IvParameterSpec ivParameterSpec = getIv();
  30. Cipher cipher = Cipher.getInstance(AlgorithmProvider);
  31. cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
  32. byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
  33. return cipherBytes;
  34. }
  35. public static byte[] decrypt(String src, byte[] key) throws Exception {
  36. SecretKey secretKey = new SecretKeySpec(key, Algorithm);
  37. IvParameterSpec ivParameterSpec = getIv();
  38. Cipher cipher = Cipher.getInstance(AlgorithmProvider);
  39. cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
  40. byte[] hexBytes = hexStringToBytes(src);
  41. byte[] plainBytes = cipher.doFinal(hexBytes);
  42. return plainBytes;
  43. }
  44. /**
  45. * 解密
  46. * @param src
  47. * @param keyStr
  48. * @return
  49. * @throws Exception
  50. */
  51. public static String decryptStr(String src, String keyStr) throws Exception {
  52. byte key[] = keyStr.getBytes("utf-8");
  53. SecretKey secretKey = new SecretKeySpec(key, Algorithm);
  54. IvParameterSpec ivParameterSpec = getIv();
  55. Cipher cipher = Cipher.getInstance(AlgorithmProvider);
  56. cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
  57. byte[] hexBytes = hexStringToBytes(src);
  58. byte[] plainBytes = cipher.doFinal(hexBytes);
  59. return new String(plainBytes,"UTF-8");
  60. }
  61. public static String encrypt(String src, String keyStr) throws NoSuchAlgorithmException, NoSuchPaddingException,
  62. InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
  63. byte key[] = keyStr.getBytes("utf-8");
  64. SecretKey secretKey = new SecretKeySpec(key, Algorithm);
  65. IvParameterSpec ivParameterSpec = getIv();
  66. Cipher cipher = Cipher.getInstance(AlgorithmProvider);
  67. cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
  68. byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
  69. return new String(cipherBytes,"UTF-8");
  70. }
  71. public static void main(String args[]){
  72. try {
  73. String passwordMd5 = MD5Util.MD5("123456");
  74. System.out.println("加密后密码:"+passwordMd5);
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. /**
  80. * 将byte转换为16进制字符串
  81. * @param src
  82. * @return
  83. */
  84. public static String byteToHexString(byte[] src) {
  85. StringBuilder sb = new StringBuilder();
  86. for (int i = 0; i < src.length; i++) {
  87. int v = src[i] & 0xff;
  88. String hv = Integer.toHexString(v);
  89. if (hv.length() < 2) {
  90. sb.append("0");
  91. }
  92. sb.append(hv);
  93. }
  94. return sb.toString();
  95. }
  96. /**
  97. * 将16进制字符串装换为byte数组
  98. * @param hexString
  99. * @return
  100. */
  101. public static byte[] hexStringToBytes(String hexString) {
  102. hexString = hexString.toUpperCase();
  103. int length = hexString.length() / 2;
  104. char[] hexChars = hexString.toCharArray();
  105. byte[] b = new byte[length];
  106. for (int i = 0; i < length; i++) {
  107. int pos = i * 2;
  108. b[i] = (byte) (charToByte(hexChars[pos]) << 4 | (charToByte(hexChars[pos + 1]))& 0xff);
  109. }
  110. return b;
  111. }
  112. private static byte charToByte(char c) {
  113. return (byte) "0123456789ABCDEF".indexOf(c);
  114. }
  115. /*public static void main(String[] args) {
  116. try {
  117. // byte key[] = generatorKey();
  118. System.out.println("FUjs@17654HGJKKn".length());
  119. // 密钥必须是16的倍数
  120. byte key[] = "FUjs@17654HGJKKn".getBytes("utf-8");//hexStringToBytes("0123456789ABCDEF");
  121. String src = "usersrs=111111?sdfjsalkj=1mlkjklasjdfkls?sss=sdfsjlk1123123123?sdd=453456465432165765432221351567897654132";
  122. System.out.println("密钥:"+byteToHexString(key));
  123. System.out.println("原字符串:"+src);
  124. String enc = byteToHexString(encrypt(src, key));
  125. System.out.println("加密:"+enc);
  126. System.out.println("解密:"+decryptStr(enc, AESUtils.key));
  127. } catch (InvalidKeyException e) {
  128. e.printStackTrace();
  129. } catch (NoSuchAlgorithmException e) {
  130. e.printStackTrace();
  131. } catch (NoSuchPaddingException e) {
  132. e.printStackTrace();
  133. } catch (IllegalBlockSizeException e) {
  134. e.printStackTrace();
  135. } catch (BadPaddingException e) {
  136. e.printStackTrace();
  137. } catch (UnsupportedEncodingException e) {
  138. e.printStackTrace();
  139. } catch (Exception e) {
  140. e.printStackTrace();
  141. }
  142. }*/
  143. }

(2):

  1. package com.demo.util;
  2. import org.apache.commons.codec.digest.DigestUtils;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.io.UnsupportedEncodingException;
  6. import java.security.MessageDigest;
  7. import java.security.NoSuchAlgorithmException;
  8. import java.util.*;
  9. /**
  10. * Md5算法加密
  11. *
  12. * @author <a href="mailTo:helen@ibw.cn">Helen</a>
  13. * @time Mar 19, 2013
  14. * @version 1.0
  15. */
  16. public class MD5Util {
  17. private final static Logger logger = LoggerFactory.getLogger(MD5Util.class);
  18. private final static String APP_KEY="hYHN#1son@16faEV2";
  19. private final static String CHARSET="UTF-8";
  20. /**
  21. * MD5加密算法
  22. *
  23. * @param s
  24. * @return
  25. */
  26. public final static String MD5(String s) throws NoSuchAlgorithmException {
  27. char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  28. 'A', 'B', 'C', 'D', 'E', 'F' };
  29. byte[] btInput = s.getBytes();
  30. // 获得MD5摘要算法的 MessageDigest 对象
  31. MessageDigest mdInst;
  32. mdInst = MessageDigest.getInstance("MD5");
  33. // 使用指定的字节更新摘要
  34. mdInst.update(btInput);
  35. // 获得密文
  36. byte[] md = mdInst.digest();
  37. // 把密文转换成十六进制的字符串形式
  38. int j = md.length;
  39. char str[] = new char[j * 2];
  40. int k = 0;
  41. for (int i = 0; i < j; i++) {
  42. byte byte0 = md[i];
  43. str[k++] = hexDigits[byte0 >>> 4 & 0xf];
  44. str[k++] = hexDigits[byte0 & 0xf];
  45. }
  46. return new String(str);
  47. }
  48. /**
  49. * 编码转换
  50. * @param content
  51. * @param charset
  52. * @return
  53. * @throws UnsupportedEncodingException
  54. */
  55. private static byte[] getContentBytes(String content, String charset) {
  56. if (charset == null || "".equals(charset)) {
  57. return content.getBytes();
  58. }
  59. try {
  60. return content.getBytes(charset);
  61. } catch (UnsupportedEncodingException e) {
  62. throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
  63. }
  64. }
  65. public static String sign(String prestr){
  66. String mysign = DigestUtils.md5Hex(getContentBytes(prestr + APP_KEY, CHARSET));
  67. return mysign;
  68. }
  69. public static String signParams(Map<String,String> params){
  70. try {
  71. if (params != null && params.size()>0){
  72. List<Map.Entry<String, String>> list = new ArrayList(params.entrySet());
  73. Collections.sort(list, new Comparator<Map.Entry<String,String>>() {
  74. @Override
  75. public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
  76. return o1.getKey().compareTo(o2.getKey());
  77. }
  78. });
  79. StringBuffer sb = new StringBuffer();
  80. for (Map.Entry<String, String> ent:list) {
  81. sb.append(ent.getKey());
  82. sb.append(ent.getValue());
  83. }
  84. logger.info("原字符串:{}",sb.toString());
  85. return sign(sb.toString());
  86. }
  87. }catch (Exception e){
  88. }
  89. return "";
  90. }
  91. public static boolean isSign(HashMap<String,String> params,String sign){
  92. try{
  93. String newSign = signParams(params);
  94. logger.info("原签名:{}",sign);
  95. logger.info("新签名:{}",newSign);
  96. if (Objects.equals(sign,newSign)){
  97. return true;
  98. }
  99. }catch (Exception e){
  100. }
  101. return false;
  102. }
  103. }

(3):

  1. package com.demo.util;
  2. import com.demo.constants.Constants;
  3. import com.demo.exception.TokenException;
  4. import com.demo.factory.ServiceFactory;
  5. import io.jsonwebtoken.*;
  6. import org.apache.commons.lang.StringUtils;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.util.Date;
  12. /**
  13. * token管理器
  14. */
  15. public class JwtProvider {
  16. private static final Logger logger = LoggerFactory.getLogger(JwtProvider.class);
  17. private static RedisClient redisClient;
  18. static {
  19. redisClient = ServiceFactory.getInstance().createRedisClient();
  20. }
  21. /**
  22. * 生成token并将token写入redis
  23. * @param res
  24. * @param username
  25. * @return
  26. */
  27. public static String addAuthentication(HttpServletResponse res, String username){
  28. String jwtStr = Jwts.builder()
  29. .setSubject(username)
  30. .setExpiration(new Date(System.currentTimeMillis() + Constants.EXPIRATIONTIME))
  31. .signWith(SignatureAlgorithm.HS512, Constants.SECRET)
  32. .compact();
  33. String tokent = jwtStr;
  34. res.addHeader(Constants.HEADER_STRING,tokent );
  35. //每次重置token,实现单一点登录
  36. redisClient.set(Constants.TOKEN_JWT+username,tokent);
  37. return tokent;
  38. }
  39. /**
  40. * 从token中获取username
  41. * @param req
  42. * @return
  43. */
  44. public static String getAuthentication(HttpServletRequest req){
  45. String token = req.getHeader(Constants.HEADER_STRING);
  46. String username = null;
  47. if(!StringUtils.isEmpty(token)){
  48. try{
  49. // parse the jwt
  50. username = Jwts.parser()
  51. .setSigningKey(Constants.SECRET)
  52. .parseClaimsJws(token)
  53. .getBody()
  54. .getSubject();
  55. }catch (ExpiredJwtException e) {
  56. logger.error("Token已过期: {} " + e);
  57. throw new TokenException("Token已过期");
  58. } catch (UnsupportedJwtException e) {
  59. logger.error("Token格式错误: {} " + e);
  60. throw new TokenException("Token格式错误");
  61. } catch (MalformedJwtException e) {
  62. logger.error("Token没有被正确构造: {} " + e);
  63. throw new TokenException("Token没有被正确构造");
  64. } catch (SignatureException e) {
  65. logger.error("签名失败: {} " + e);
  66. throw new TokenException("签名失败");
  67. } catch (IllegalArgumentException e) {
  68. logger.error("非法参数异常: {} " + e);
  69. throw new TokenException("非法参数异常");
  70. }
  71. }
  72. return username;
  73. }
  74. }

(4):

  1. package com.demo.util;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Component;
  7. import redis.clients.jedis.Jedis;
  8. import redis.clients.jedis.JedisPool;
  9. import redis.clients.jedis.JedisPoolConfig;
  10. import java.io.ByteArrayInputStream;
  11. import java.io.ByteArrayOutputStream;
  12. import java.io.ObjectInputStream;
  13. import java.io.ObjectOutputStream;
  14. import java.lang.reflect.Field;
  15. import java.util.*;
  16. @Component
  17. public class RedisClient {
  18. private final Logger logger = LoggerFactory.getLogger(RedisClient.class);
  19. private final String SUCCESS_OK = "OK";
  20. private final Long SUCCESS_STATUS_LONG = 1L;
  21. // SET IF NOT EXIST,即当key不存在时,我们进行set操作;若key已经存在,则不做任何操作
  22. private final String SET_IF_NOT_EXIST = "NX";
  23. //key加一个过期的设置,具体时间由第五个参数决定
  24. private final String SET_WITH_EXPIRE_TIME = "PX";
  25. private static JedisPool jedisPool;
  26. private static final String IP = "127.0.0.1"; // ip
  27. private static final int PORT = 6379; // 端口
  28. // private static final String AUTH=""; // 密码(原始默认是没有密码)
  29. private static int MAX_ACTIVE = 1024; // 最大连接数
  30. private static int MAX_IDLE = 200; // 设置最大空闲数
  31. private static int MAX_WAIT = 10000; // 最大连接时间
  32. private static int TIMEOUT = 10000; // 超时时间
  33. private static boolean BORROW = true; // 在borrow一个事例时是否提前进行validate操作
  34. /**
  35. * 初始化线程池
  36. */
  37. static {
  38. JedisPoolConfig config = new JedisPoolConfig();
  39. config.setMaxTotal(MAX_ACTIVE);
  40. config.setMaxIdle(MAX_IDLE);
  41. config.setMaxWaitMillis(MAX_WAIT);
  42. config.setTestOnBorrow(BORROW);
  43. jedisPool = new JedisPool(config, IP, PORT, TIMEOUT);
  44. }
  45. public JedisPool getJedisPool(){
  46. return jedisPool;
  47. }
  48. /**
  49. * 字符串set
  50. *
  51. * @param key
  52. * @param value
  53. * @return
  54. */
  55. public boolean set(String key, String value) {
  56. boolean ret = false;
  57. Jedis jedis = null;
  58. try {
  59. jedis = jedisPool.getResource();
  60. if (jedis == null) {
  61. return ret;
  62. }
  63. String status = jedis.set(key, value);
  64. if (SUCCESS_OK.equalsIgnoreCase(status)) {
  65. ret = true;
  66. }
  67. } catch (Exception e) {
  68. logger.error("redis set 出错", e);
  69. jedisPool.returnBrokenResource(jedis);
  70. } finally {
  71. if (null != jedis) {
  72. jedisPool.returnResource(jedis);
  73. }
  74. }
  75. return ret;
  76. }
  77. /**
  78. * 字符串set
  79. *
  80. * @param key
  81. * @param value
  82. * @param seconds
  83. * 单位秒,大于0
  84. * @return
  85. */
  86. public boolean set(String key, String value, int seconds) {
  87. boolean ret = false;
  88. Jedis jedis = null;
  89. try {
  90. jedis = jedisPool.getResource();
  91. if (jedis == null) {
  92. return ret;
  93. }
  94. String status = jedis.setex(key, seconds, value);
  95. if (SUCCESS_OK.equalsIgnoreCase(status)) {
  96. ret = true;
  97. }
  98. } catch (Exception e) {
  99. logger.error("redis set 出错", e);
  100. jedisPool.returnBrokenResource(jedis);
  101. } finally {
  102. if (null != jedis) {
  103. jedisPool.returnResource(jedis);
  104. }
  105. }
  106. return ret;
  107. }
  108. public boolean set(byte[] key, int seconds, byte[] value) {
  109. boolean ret = false;
  110. Jedis jedis = null;
  111. try {
  112. jedis = jedisPool.getResource();
  113. if (jedis == null) {
  114. return ret;
  115. }
  116. String status = jedis.setex(key, seconds, value);
  117. if (SUCCESS_OK.equalsIgnoreCase(status)) {
  118. ret = true;
  119. }
  120. } catch (Exception e) {
  121. logger.error("redis set 出错", e);
  122. jedisPool.returnBrokenResource(jedis);
  123. } finally {
  124. if (null != jedis) {
  125. jedisPool.returnResource(jedis);
  126. }
  127. }
  128. return ret;
  129. }
  130. /**
  131. * 是否存在key
  132. *
  133. * @param key
  134. * @return
  135. */
  136. public boolean isExists(String key) {
  137. boolean ret = false;
  138. Jedis jedis = null;
  139. try {
  140. jedis = jedisPool.getResource();
  141. if (jedis == null) {
  142. return ret;
  143. }
  144. return jedis.exists(key);
  145. } catch (Exception e) {
  146. logger.error("redis isExists 出错", e);
  147. jedisPool.returnBrokenResource(jedis);
  148. } finally {
  149. if (null != jedis) {
  150. jedisPool.returnResource(jedis);
  151. }
  152. }
  153. return ret;
  154. }
  155. /**
  156. * 字符串 删除
  157. *
  158. * @param key
  159. * @return
  160. */
  161. public boolean del(byte[] key) {
  162. boolean ret = false;
  163. Jedis jedis = null;
  164. try {
  165. jedis = jedisPool.getResource();
  166. if (jedis == null) {
  167. return ret;
  168. }
  169. Long status = jedis.del(key);
  170. if (Objects.equals(SUCCESS_STATUS_LONG,status)) {
  171. ret = true;
  172. }
  173. } catch (Exception e) {
  174. logger.error("redis del 出错", e);
  175. jedisPool.returnBrokenResource(jedis);
  176. } finally {
  177. if (null != jedis) {
  178. jedisPool.returnResource(jedis);
  179. }
  180. }
  181. return ret;
  182. }
  183. public boolean del(String key) {
  184. boolean ret = false;
  185. Jedis jedis = null;
  186. try {
  187. jedis = jedisPool.getResource();
  188. if (jedis == null) {
  189. return ret;
  190. }
  191. Long status = jedis.del(key);
  192. if (Objects.equals(SUCCESS_STATUS_LONG,status)) {
  193. ret = true;
  194. }
  195. } catch (Exception e) {
  196. logger.error("redis del 出错", e);
  197. jedisPool.returnBrokenResource(jedis);
  198. } finally {
  199. if (null != jedis) {
  200. jedisPool.returnResource(jedis);
  201. }
  202. }
  203. return ret;
  204. }
  205. /**
  206. * 字符串获取
  207. *
  208. * @param key
  209. * @return
  210. */
  211. public String get(String key) {
  212. String ret = null;
  213. Jedis jedis = null;
  214. try {
  215. jedis = jedisPool.getResource();
  216. if (jedis == null) {
  217. return ret;
  218. }
  219. ret = jedis.get(key);
  220. } catch (Exception e) {
  221. logger.error("redis get 出错", e);
  222. jedisPool.returnBrokenResource(jedis);
  223. } finally {
  224. if (null != jedis) {
  225. jedisPool.returnResource(jedis);
  226. }
  227. }
  228. return ret;
  229. }
  230. public Long ttl(String key){
  231. Long ret = null;
  232. Jedis jedis = null;
  233. try {
  234. jedis = jedisPool.getResource();
  235. if (jedis == null) {
  236. return ret;
  237. }
  238. ret = jedis.ttl(key);
  239. } catch (Exception e) {
  240. logger.error("redis get 出错", e);
  241. jedisPool.returnBrokenResource(jedis);
  242. } finally {
  243. if (null != jedis) {
  244. jedisPool.returnResource(jedis);
  245. }
  246. }
  247. return ret;
  248. }
  249. public byte[] get(byte[] key) {
  250. byte[] ret = null;
  251. Jedis jedis = null;
  252. try {
  253. jedis = jedisPool.getResource();
  254. if (jedis == null) {
  255. return ret;
  256. }
  257. ret = jedis.get(key);
  258. } catch (Exception e) {
  259. logger.error("redis get 出错", e);
  260. jedisPool.returnBrokenResource(jedis);
  261. } finally {
  262. if (null != jedis) {
  263. jedisPool.returnResource(jedis);
  264. }
  265. }
  266. return ret;
  267. }
  268. /**
  269. * 获取分布式锁
  270. *
  271. * @param lockKey
  272. * key为锁
  273. * @param requestId
  274. * 加锁请求
  275. * @param expireTime
  276. * key的过期时间
  277. * @return
  278. */
  279. public boolean getLock(String lockKey, String requestId, int expireTime) {
  280. boolean ret = false;
  281. Jedis jedis = null;
  282. try {
  283. jedis = jedisPool.getResource();
  284. if (jedis == null) {
  285. return ret;
  286. }
  287. String status = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
  288. if (SUCCESS_OK.equalsIgnoreCase(status)) {
  289. ret = true;
  290. }
  291. } catch (Exception e) {
  292. logger.error("redis 获取分布式锁 出错", e);
  293. jedisPool.returnBrokenResource(jedis);
  294. } finally {
  295. if (null != jedis) {
  296. jedisPool.returnResource(jedis);
  297. }
  298. }
  299. return ret;
  300. }
  301. /**
  302. * 释放分布式锁
  303. *
  304. * @param lockKey
  305. * @param requestId
  306. */
  307. public boolean releaseLock(String lockKey, String requestId) {
  308. boolean ret = false;
  309. Jedis jedis = null;
  310. try {
  311. jedis = jedisPool.getResource();
  312. if (jedis == null) {
  313. return ret;
  314. }
  315. /*
  316. * 其他请求误解锁问题 if(requestId.equals(jedis.get(lockKey))) { jedis.del(lockKey); }
  317. */
  318. String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
  319. Object status = jedis.eval(script, Collections.singletonList(lockKey),
  320. Collections.singletonList(requestId));
  321. if (SUCCESS_STATUS_LONG.equals(status)) {
  322. ret = true;
  323. }
  324. } catch (Exception e) {
  325. logger.error("redis 释放分布式锁 出错", e);
  326. jedisPool.returnBrokenResource(jedis);
  327. } finally {
  328. if (null != jedis) {
  329. jedisPool.returnResource(jedis);
  330. }
  331. }
  332. return ret;
  333. }
  334. /**
  335. * 序列化存入对象
  336. *
  337. * @param key
  338. * @param obj
  339. * @return
  340. */
  341. public boolean set(byte[] key, Object obj) {
  342. boolean ret = false;
  343. Jedis jedis = null;
  344. try {
  345. jedis = jedisPool.getResource();
  346. if (jedis == null) {
  347. return ret;
  348. }
  349. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  350. ObjectOutputStream oos = new ObjectOutputStream(baos);
  351. oos.writeObject(obj);
  352. String status = jedis.set(key, baos.toByteArray());
  353. if (SUCCESS_OK.equalsIgnoreCase(status)) {
  354. ret = true;
  355. }
  356. } catch (Exception e) {
  357. logger.error("redis set 出错", e);
  358. jedisPool.returnBrokenResource(jedis);
  359. } finally {
  360. if (null != jedis) {
  361. jedisPool.returnResource(jedis);
  362. }
  363. }
  364. return ret;
  365. }
  366. /**
  367. * 取序列化对象
  368. *
  369. * @param key
  370. * @return
  371. */
  372. public Object getObj(byte[] key) {
  373. Object ret = null;
  374. Jedis jedis = null;
  375. try {
  376. jedis = jedisPool.getResource();
  377. if (jedis == null) {
  378. return ret;
  379. }
  380. byte[] rets = jedis.get(key);
  381. ByteArrayInputStream bais = new ByteArrayInputStream(rets);
  382. ObjectInputStream ois = new ObjectInputStream(bais);
  383. return ois.readObject();
  384. } catch (Exception e) {
  385. logger.error("redis get 出错", e);
  386. jedisPool.returnBrokenResource(jedis);
  387. } finally {
  388. if (null != jedis) {
  389. jedisPool.returnResource(jedis);
  390. }
  391. }
  392. return ret;
  393. }
  394. /**
  395. * hash数据类型存储对象
  396. *
  397. * @param key
  398. * @param obj
  399. * @return
  400. */
  401. public boolean setHm(String key, Object obj) {
  402. boolean ret = false;
  403. Jedis jedis = null;
  404. try {
  405. jedis = jedisPool.getResource();
  406. if (jedis == null) {
  407. return ret;
  408. }
  409. Map<String, String> hash = objToMap(obj);
  410. String status = jedis.hmset(key, hash);
  411. if (SUCCESS_OK.equalsIgnoreCase(status)) {
  412. ret = true;
  413. }
  414. } catch (Exception e) {
  415. logger.error("redis setHm 出错", e);
  416. jedisPool.returnBrokenResource(jedis);
  417. } finally {
  418. if (null != jedis) {
  419. jedisPool.returnResource(jedis);
  420. }
  421. }
  422. return ret;
  423. }
  424. /**
  425. * 修改对象属性
  426. *
  427. * @param key
  428. * @param field
  429. * @param value
  430. * @return
  431. */
  432. public boolean setHm(String key, String field, String value) {
  433. boolean ret = false;
  434. Jedis jedis = null;
  435. try {
  436. jedis = jedisPool.getResource();
  437. if (jedis == null) {
  438. return ret;
  439. }
  440. Long status = jedis.hset(key, field, value);
  441. if (0L == status) {
  442. ret = true;
  443. }
  444. } catch (Exception e) {
  445. logger.error("redis setHm 出错", e);
  446. jedisPool.returnBrokenResource(jedis);
  447. } finally {
  448. if (null != jedis) {
  449. jedisPool.returnResource(jedis);
  450. }
  451. }
  452. return ret;
  453. }
  454. /**
  455. * 根据fields 查询key对象属性列表
  456. *
  457. * @param key
  458. * @param fields
  459. * @return
  460. */
  461. public List<String> getHm(String key, String... fields) {
  462. List<String> ret = null;
  463. Jedis jedis = null;
  464. try {
  465. jedis = jedisPool.getResource();
  466. if (jedis == null) {
  467. return null;
  468. }
  469. ret = jedis.hmget(key, fields);
  470. } catch (Exception e) {
  471. logger.error("redis getHm 出错", e);
  472. jedisPool.returnBrokenResource(jedis);
  473. } finally {
  474. if (null != jedis) {
  475. jedisPool.returnResource(jedis);
  476. }
  477. }
  478. return ret;
  479. }
  480. /**
  481. * 根据field 查询key对象属性
  482. *
  483. * @param key
  484. * @param
  485. * @return
  486. */
  487. public String getHm(String key, String field) {
  488. String ret = null;
  489. Jedis jedis = null;
  490. try {
  491. jedis = jedisPool.getResource();
  492. if (jedis == null) {
  493. return null;
  494. }
  495. ret = jedis.hget(key, field);
  496. } catch (Exception e) {
  497. logger.error("redis getHm 出错", e);
  498. jedisPool.returnBrokenResource(jedis);
  499. } finally {
  500. if (null != jedis) {
  501. jedisPool.returnResource(jedis);
  502. }
  503. }
  504. return ret;
  505. }
  506. /**
  507. * json格式存对象
  508. * @param key
  509. * @param obj
  510. * @return
  511. */
  512. public boolean setJson(String key,Object obj) {
  513. boolean ret = false;
  514. Jedis jedis = null;
  515. try {
  516. jedis = jedisPool.getResource();
  517. if (jedis == null) {
  518. return ret;
  519. }
  520. ObjectMapper mapper = new ObjectMapper();
  521. String status = jedis.set(key, mapper.writeValueAsString(obj));
  522. if (SUCCESS_OK.equalsIgnoreCase(status)) {
  523. ret = true;
  524. }
  525. } catch (Exception e) {
  526. logger.error("redis setJson 出错", e);
  527. jedisPool.returnBrokenResource(jedis);
  528. } finally {
  529. if (null != jedis) {
  530. jedisPool.returnResource(jedis);
  531. }
  532. }
  533. return ret;
  534. }
  535. /**
  536. * json格式取对象
  537. * @param key
  538. * @param clazz
  539. * @return
  540. */
  541. public Object getJson(String key,Class clazz) {
  542. Object ret = null;
  543. Jedis jedis = null;
  544. try {
  545. jedis = jedisPool.getResource();
  546. if (jedis == null) {
  547. return ret;
  548. }
  549. String str = jedis.get(key);
  550. ObjectMapper mapper = new ObjectMapper();
  551. ret = mapper.readValue(str, clazz);
  552. } catch (Exception e) {
  553. logger.error("redis getJson 出错", e);
  554. jedisPool.returnBrokenResource(jedis);
  555. } finally {
  556. if (null != jedis) {
  557. jedisPool.returnResource(jedis);
  558. }
  559. }
  560. return ret;
  561. }
  562. private HashMap<String, String> objToMap(Object obj) {
  563. if(null == obj) {
  564. return null;
  565. }
  566. HashMap<String, String> map = new HashMap<String, String>();
  567. Field[] fields = obj.getClass().getDeclaredFields();
  568. try {
  569. for (int i = 0; i < fields.length; i++) {
  570. String varName = fields[i].getName();
  571. boolean accessFlag = fields[i].isAccessible();
  572. fields[i].setAccessible(true);
  573. Object o = fields[i].get(obj);
  574. if (o != null) {
  575. map.put(varName, o.toString());
  576. }
  577. fields[i].setAccessible(accessFlag);
  578. }
  579. } catch (Exception e) {
  580. }
  581. return map;
  582. }
  583. /**
  584. * 设置一个key的过期的秒数
  585. *
  586. * @param keyFormat
  587. * key标识
  588. * @param seconds
  589. * 过期的秒数
  590. * @param keyValues
  591. * key变量
  592. * @return 1表示设置成功, 0 表示设置失败或者无法被设置
  593. */
  594. public Long expire(String key, int seconds) {
  595. Jedis jedis = null;
  596. try {
  597. jedis =jedisPool.getResource();
  598. return jedis.expire(key, seconds);
  599. } finally {
  600. if (jedis != null) {
  601. jedis.close();
  602. }
  603. }
  604. }
  605. }

12、启动类:

  1. package com.demo;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.annotation.ImportResource;
  5. @SpringBootApplication
  6. @ImportResource("classpath:consumer.xml")
  7. public class RestStart {
  8. public static void main(String args[]){
  9. SpringApplication.run(RestStart.class,args);
  10. }
  11. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53879
推荐阅读
相关标签
  

闽ICP备14008679号