SpringBoot项目中使用Redis,Mybatis和JWT
以下是一个简化的Spring Boot项目中整合Redis, MyBatis和JWT的示例:
- 在
pom.xml
中添加依赖:
<!-- Spring Boot Starter for Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
- 配置
application.properties
或application.yml
文件:
# Redis
spring.redis.host=localhost
spring.redis.port=6379
# MyBatis
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.package.model
# JWT
jwt.secret=your_secret_key
jwt.expiration=3600000
- 创建Redis配置类:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
final RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
return template;
}
}
- 创建JWT工具类:
@Component
public class JwtTokenUtil {
private String secret;
private long expiration;
public JwtTokenUtil(@Value("${jwt.secret}") String secret,
@Value("${jwt.expiration}") long expiration) {
this.secret = secret;
this.expiration = expiration;
}
public String generateToken(UserDetails userDetails) {
return Jwts.builder()
.setSubject(userDetails.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + expiration))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public boolean validateToken(String token, UserDetails userDetails) {
String username = Jwts.parser()
评论已关闭