AgileBoot - 如何集成內置數據庫H2和內置Redis( 二 )

可以發現Mysql的建表語句需要刪除一部分特殊用法,才能在H2執行 。H2的建表語句顯得很簡單 。
3.yml中引入變量控制是否啟用H2數據庫# 如果需要無Mysql無Redis直接啟動的話可以將這個參數置為true, 并且spring.profile.active: dev換成testagileboot:embedded-test: false因為項目可以選擇使用Mysql啟動也可以使用H2啟動,Spring的配置會有沖突 。所以使用agileboot.embedded-test的值來決定啟動Mysql相關的Bean還是H2相關的Bean.Spring提供了@ConditionalOnExpression注解基于條件來初始化bean
@Bean@ConfigurationProperties("spring.datasource.druid.master")@ConditionalOnExpression("'${agileboot.embedded-test}' != 'true'")public DataSource masterDataSource(DruidProperties druidProperties) {DruidDataSource dataSource = DruidDataSourceBuilder.create().build();return druidProperties.dataSource(dataSource);}引入內置Redis代碼實現1.引入依賴<dependency><groupId>it.ozimov</groupId><artifactId>embedded-redis</artifactId><version>0.7.3</version><!-- 不排除掉slf4j的話 會沖突--><exclusions><exclusion><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId></exclusion></exclusions></dependency>2.引入Embedded Redis進行啟動@Configuration@ConditionalOnExpression("'${agileboot.embedded-test}' == 'true'")public class EmbeddedRedisConfig {@Value("${spring.redis.port}")private Integer port;private RedisServer redisServer;@PostConstructpublic void postConstruct() {RedisServer redisServer = RedisServer.builder().port(port).setting("maxheap 32M").setting("daemonize no").setting("appendonly no").build();this.redisServer = redisServer;redisServer.start();}@PreDestroypublic void preDestroy() {redisServer.stop();}}同理,我們使用agileboot.embedded-test的值來決定啟動內置的Redis.
該設計實現在AgileBoot項目內,有興趣的小伙伴可以項目down下來看下~幾行指令即可run起前后端項目 。后端項目僅需把yml的這兩個配置改一下即可 。

AgileBoot - 如何集成內置數據庫H2和內置Redis

文章插圖
前后端全棧技術交流群:1398880
歡迎前后端萌新大佬加群討論~~
【AgileBoot - 如何集成內置數據庫H2和內置Redis】

推薦閱讀