springboot+Mybatis+Redis项目搭建(非常适合新上手springboot或不经常用java写后端的朋友)
以下是一个简化的Spring Boot + MyBatis + Redis项目的基本架构示例:
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring Boot Starter for Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Spring Boot Starter for MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- Database Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.yourpackage.model
spring.redis.host=localhost
spring.redis.port=6379
- 创建一个Redis配置类:
@Configuration
public class RedisConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(CacheConfiguration.defaultCacheConfig())
.build();
}
}
- 创建一个MyBatis的Mapper接口:
@Mapper
public interface YourModelMapper {
// 定义操作数据库的方法
}
- 创建一个Service层:
@Service
public class YourModelService {
@Autowired
private YourModelMapper yourModelMapper;
@Cacheable("yourCacheName")
public YourModel getById(Integer id) {
return yourModelMapper.selectByPrimaryKey(id);
评论已关闭