SpringBoot2.x连接自定义前缀的redis

本文详细介绍了如何在SpringBoot项目中配置并使用Redis,包括配置文件的设置、依赖引入、连接工厂创建及序列化处理。通过实例展示了如何自定义配置读取,以及如何实现Redis的数据操作。

因为项目需要,需通过统一配置中心读取redis的配置信息,而springBoot默认读取的配置信息的前缀为 spring.redis。

步骤如下:

1.需要读取的配置文件 redis.properties

redis.host=192.168.1.10
redis.port=6379

2.程序启动读取配置文件

SpringBoot启动类添加注解   @PropertySource(value = {"classpath:config/redis.properties"})

@SpringBootApplication
@PropertySource(value = {"classpath:config/redis.properties"})
public class Application {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(KscrmApplication.class, args);
    }
}

3.配置RedisConnectionFactory初始化时读取文件中等值

(1)引入相关依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
     <groupId>redis.clients</groupId>
     <artifactId>jedis</artifactId>
     <version>2.9.0</version>
</dependency>

(2)配置类

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Component
public class RedisAutoConfiguration {

    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private int port;

    @Bean
    public RedisConnectionFactory connectionFactory() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        JedisClientConfiguration clientConfig = JedisClientConfiguration.builder()
                .usePooling().poolConfig(poolConfig).and().build();
        // 单点redis
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
        redisConfig.setHostName(host);
        redisConfig.setPort(port);

        return new JedisConnectionFactory(redisConfig,clientConfig);
    }

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate() {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        //使用fastjson序列化
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        // value值的序列化采用fastJsonRedisSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        template.setConnectionFactory(connectionFactory());
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(connectionFactory());
        return template;
    }

}

其中FastJsonRedisSerializer类为序列化相关类

public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    public FastJsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (null == t) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);

    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (null == bytes || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return (T) JSON.parseObject(str, clazz);

    }
}

 

<think>好的,用户现在想了解如何使用Spring Boot 3.x、Spring Security、OAuth2、JWT、Redis和MySQL来实现一个用户系统。我需要先理清楚各个组件的作用以及如何整合它们。 首先,Spring Boot 3.x的版本需要注意依赖的兼容性,特别是Spring Security和OAuth2相关的库。用户提到OAuth2,但Spring官方现在推荐使用Spring Security OAuth2已被弃用,转而由Spring Security直接支持OAuth2。所以可能需要确认在Spring Boot 3.x中如何正确集成OAuth2和JWT。 接下来是Spring Security的配置。用户需要实现用户认证和授权,可能需要自定义UserDetailsService来从MySQL数据库中加载用户信息。JWT用于生成和验证令牌,这需要创建JWT工具类,处理令牌的生成、解析和刷新。Redis的作用可能是用来存储令牌或者缓存用户信息,提高性能。 然后,数据库方面,用户使用MySQL,所以需要设计用户表、角色表以及可能的权限表,并通过MyBatis-Plus进行数据操作。此外,OAuth2的配置可能需要定义授权服务器和资源服务器,但由于Spring Security 5.x之后的变化,可能需要使用新的配置方式,比如使用@EnableWebSecurity和自定义配置类。 版本兼容性是一个大问题,比如Spring Boot 3.x需要Java 17及以上,依赖的Spring Security版本可能较高,需要确认OAuth2相关的依赖是否兼容。用户提供的引用中提到了一些旧版本的配置,比如spring-security-oauth22.3.3.RELEASE,但可能在Spring Boot 3.x中已经不适用,需要寻找替代方案。 另外,JWT的集成需要生成令牌,并在Spring Security的过滤器链中添加JWT验证的过滤器。还需要处理令牌的存储和刷新机制,可能使用Redis来存储黑名单或有效令牌,以实现令牌的失效管理。 可能遇到的问题包括依赖冲突、配置错误、过滤器顺序不当导致的功能异常,以及权限配置不正确导致的访问控制失效。需要确保各个组件按正确的顺序配置,并进行充分的测试。 总结步骤大致如下: 1. 项目初始化,配置正确的依赖版本。 2. 数据库设计,集成MyBatis-Plus和MySQL。 3. 实现UserDetailsService和UserDetails,从数据库加载用户信息。 4. 配置Spring Security,设置认证和授权规则。 5. 创建JWT工具类,处理令牌的生成和验证。 6. 集成Redis,管理令牌状态。 7. 配置OAuth2授权服务器和资源服务器(可能需要使用Spring Security的新方式)。 8. 测试各个接口,确保认证和授权正常工作。 需要验证每个步骤的配置是否正确,特别是新版本中的变更点,避免因为版本升级导致的配置失效。此外,参考用户提供的引用中的部分配置,但需要调整以适应Spring Boot 3.x的变化。</think>### Spring Boot 3.x + Spring Security + OAuth2 + JWT + Redis + MySQL 用户系统实现方案 #### 一、技术选型与版本适配 1. **Spring Boot 3.x**:需使用Java 17+,注意依赖版本兼容性 2. **Spring Security 6.x**:已内置OAuth2核心功能,不再需要`spring-security-oauth2`独立库[^1][^3] 3. **JWT**:使用`jjwt`库(0.12.x+适配Java 17) 4. **Redis**:存储令牌黑名单/会话管理 5. **MySQL**:用户数据存储 #### 二、项目搭建步骤 ##### 1. 依赖配置(pom.xml) ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.12.3</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.12.3</version> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.5</version> </dependency> ``` ##### 2. 数据库设计(MySQL) ```sql CREATE TABLE sys_user ( id BIGINT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) UNIQUE NOT NULL, password VARCHAR(100) NOT NULL, enabled BOOLEAN DEFAULT true ); CREATE TABLE sys_role ( id BIGINT PRIMARY KEY AUTO_INCREMENT, role_name VARCHAR(20) UNIQUE NOT NULL ); CREATE TABLE user_role ( user_id BIGINT, role_id BIGINT, PRIMARY KEY(user_id, role_id) ); ``` ##### 3. Spring Security配置类 ```java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth .requestMatchers("/auth/login").permitAll() .anyRequest().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt .decoder(jwtDecoder()))); return http.build(); } @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withSecretKey(jwtSecretKey()).build(); } @Bean public SecretKey jwtSecretKey() { return Keys.hmacShaKeyFor(Decoders.BASE64.decode("your-256-bit-secret")); } } ``` ##### 4. JWT工具类 ```java public class JwtUtils { private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor( Decoders.BASE64.decode("your-256-bit-secret")); public static String generateToken(UserDetails user) { return Jwts.builder() .subject(user.getUsername()) .issuedAt(new Date()) .expiration(new Date(System.currentTimeMillis() + 86400000)) // 24小时 .signWith(SECRET_KEY) .compact(); } public static Claims parseToken(String token) { return Jwts.parser() .verifyWith(SECRET_KEY) .build() .parseSignedClaims(token) .getPayload(); } } ``` ##### 5. Redis集成配置 ```yaml spring: redis: host: localhost port: 6379 datasource: url: jdbc:mysql://localhost:3306/auth_db username: root password: root ``` ##### 6. 自定义UserDetailsService ```java @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String username) { SysUser user = userMapper.selectByUsername(username); List<SimpleGrantedAuthority> authorities = user.getRoles().stream() .map(role -> new SimpleGrantedAuthority(role.getRoleName())) .collect(Collectors.toList()); return new User(user.getUsername(), user.getPassword(), authorities); } } ``` #### 三、核心流程说明 1. **用户登录**:提交凭证后,Spring Security调用`UserDetailsService`验证身份 2. **JWT生成**:验证成功后生成JWT令牌返回客户端[^2] 3. **请求鉴权**:后续请求需携带JWT,由`JwtAuthenticationFilter`解析验证 4. **权限控制**:基于角色实现接口级访问控制 5. **令牌注销**:将过期令牌存入Redis黑名单 #### 四、常见问题解决 1. **版本冲突**:确保所有Spring依赖版本与Boot 3.x兼容 2. **JWT解析失败**:检查密钥生成算法与解析配置是否一致 3. **权限不生效**:检查角色前缀配置和接口注解使用 4. **Redis连接异常**:检查Redis配置和网络连通性
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值