1.在Pom.xml添加spring-boot-starter-data-cassandra依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-cassandra</artifactId> </dependency>
啟動spring boot應用,出現錯誤:
org.springframework.boot.SpringApplication: 815 - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.class]:
Invocation of init method failed;
nested exception is com.datastax.driver.core.exceptions.NoHostAvailableException:
All host(s) tried for query failed (
tried:
localhost/127.0.0.1:9042 (com.datastax.driver.core.exceptions.TransportException: [localhost/127.0.0.1:9042] Cannot connect),
localhost/0:0:0:0:0:0:0:1:9042 (com.datastax.driver.core.exceptions.TransportException: [localhost/0:0:0:0:0:0:0:1:9042] Cannot connect))
意思是說應用啟動失敗。是由於在CassandraDataAutoConfiguration類中創建bean時失敗了。內部原因是應用啟動過程中發現cassandra不可訪問,拋出了NoHostAvailableException異常。
默認情況下boot中的自動配置的Cassandra的host是127.0.0.1和0:0:0:0:0:0:0:1,兩次嘗試都失敗了。
=>在本地的C:\Windows\System32\drivers\etc目錄中的hosts文件中添加:
192.168.99.100 localhost
將127.0.0.1映射到實際配置的ip,這里使用了在Docker中啟用的Cassandra容器。
=>spring boot提供了可以改配置的方式:
在src/main/resources目錄下添加application.properties文件,在其中添加:
spring.data.cassandra.contact-points=192.168.99.100
來修改配置信息。
