在这篇文章中,我们将使用Gradle和spring boot来创建一个将spring-mvc和Apache Cassandra数据库集成在一起的项目。
首先,我们将从Gradle配置开始
group 'com.gkatzioura'
version '1.0-SNAPSHOT'apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'buildscript {repositories {mavenCentral()}dependencies {classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE")}
}jar {baseName = 'gs-serving-web-content'version = '0.1.0'
}repositories {mavenCentral()
}sourceCompatibility = 1.8repositories {mavenCentral()
}dependencies {compile "org.springframework.boot:spring-boot-starter-thymeleaf"compile "org.springframework.data:spring-data-cassandra:1.2.2.RELEASE"compile 'org.slf4j:slf4j-api:1.6.6'compile 'ch.qos.logback:logback-classic:1.0.13'testCompile "junit:junit"
}task wrapper(type: Wrapper) {gradleVersion = '2.3'
}
我们将在我们的Cassandra数据库中创建键空间和表:
CREATE KEYSPACE IF NOT EXISTS example WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true;CREATE TABLE IF NOT EXISTS example.greetings (user text,id timeuuid,greet text,creation_date timestamp,PRIMARY KEY (user, id)
) WITH CLUSTERING ORDER BY (id DESC);
我们可以使用cqlsh运行包含cql语句的文件
cqlsh -f database_creation.cql
Cassandra连接信息将位于META-INF / cassandra.properties中
cassandra.contactpoints=localhost
cassandra.port=9042
cassandra.keyspace=example
现在,我们可以使用spring注释继续进行Cassandra配置。
package com.gkatzioura.spring.config;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.CassandraSessionFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.convert.CassandraConverter;
import org.springframework.data.cassandra.convert.MappingCassandraConverter;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;@Configuration
@PropertySource(value = {"classpath:META-INF/cassandra.properties"})
@EnableCassandraRepositories(basePackages = {"com.gkatzioura.spring"})
public class CassandraConfig {@Autowiredprivate Environment environment;private static final Logger LOGGER = LoggerFactory.getLogger(CassandraConfig.class);@Beanpublic CassandraClusterFactoryBean cluster() {CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();cluster.setContactPoints(environment.getProperty("cassandra.contactpoints"));cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port")));return cluster;}@Beanpublic CassandraMappingContext mappingContext() {return new BasicCassandraMappingContext();}@Beanpublic CassandraConverter converter() {return new MappingCassandraConverter(mappingContext());}@Beanpublic CassandraSessionFactoryBean session() throws Exception {CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();session.setCluster(cluster().getObject());session.setKeyspaceName(environment.getProperty("cassandra.keyspace"));session.setConverter(converter());session.setSchemaAction(SchemaAction.NONE);return session;}@Beanpublic CassandraOperations cassandraTemplate() throws Exception {return new CassandraTemplate(session().getObject());}}
然后,我们创建Greeting实体。
package com.gkatzioura.spring.entity;import com.datastax.driver.core.utils.UUIDs;
import org.springframework.cassandra.core.PrimaryKeyType;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKeyColumn;
import org.springframework.data.cassandra.mapping.Table;import java.util.Date;
import java.util.UUID;@Table(value = "greetings")
public class Greeting {@PrimaryKeyColumn(name = "id",ordinal = 1,type = PrimaryKeyType.CLUSTERED)private UUID id = UUIDs.timeBased();@PrimaryKeyColumn(name="user",ordinal = 0,type = PrimaryKeyType.PARTITIONED)private String user;@Column(value = "greet")private String greet;@Column(value = "creation_date")private Date creationDate;public UUID getId() {return id;}public void setId(UUID id) {this.id = id;}public Date getCreationDate() {return creationDate;}public void setCreationDate(Date creationDate) {this.creationDate = creationDate;}public String getUser() {return user;}public void setUser(String user) {this.user = user;}public String getGreet() {return greet;}public void setGreet(String greet) {this.greet = greet;}
}
为了访问数据,应该创建一个存储库。 在我们的案例中,我们将通过添加一些查询来向存储库添加一些额外的功能。
package com.gkatzioura.spring.repository;import com.gkatzioura.spring.entity.Greeting;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.NoRepositoryBean;import java.util.UUID;public interface GreetRepository extends CassandraRepository<Greeting> {@Query("SELECT*FROM greetings WHERE user=?0 LIMIT ?1")Iterable<Greeting> findByUser(String user,Integer limit);@Query("SELECT*FROM greetings WHERE user=?0 AND id<?1 LIMIT ?2")Iterable<Greeting> findByUserFrom(String user,UUID from,Integer limit);}
现在,我们可以实现控制器,以便通过http访问数据。 通过邮寄,我们可以保存“问候语”实体。 通过获取,我们可以获取收到的所有问候。 通过指定用户,我们可以使用Cassandra查询来获取特定用户的问候。
package com.gkatzioura.spring.controller;import com.gkatzioura.spring.entity.Greeting;
import com.gkatzioura.spring.repository.GreetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.ArrayList;
import java.util.Date;
import java.util.List;@RestController
public class GreetingController {@Autowiredprivate GreetRepository greetRepository;@RequestMapping(value = "/greeting",method = RequestMethod.GET)@ResponseBodypublic List<Greeting> greeting() {List<Greeting> greetings = new ArrayList<>();greetRepository.findAll().forEach(e->greetings.add(e));return greetings;}@RequestMapping(value = "/greeting/{user}/",method = RequestMethod.GET)@ResponseBodypublic List<Greeting> greetingUserLimit(@PathVariable String user,Integer limit) {List<Greeting> greetings = new ArrayList<>();greetRepository.findByUser(user,limit).forEach(e -> greetings.add(e));return greetings;}@RequestMapping(value = "/greeting",method = RequestMethod.POST)@ResponseBodypublic String saveGreeting(@RequestBody Greeting greeting) {greeting.setCreationDate(new Date());greetRepository.save(greeting);return "OK";}}
最后但并非最不重要的是我们的Application类
package com.gkatzioura.spring;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
为了运行,只需运行:
gradle bootRun
翻译自: https://www.javacodegeeks.com/2015/08/set-up-a-springdata-project-using-apache-cassandra.html