1. 序章

このチュートリアルでは、SpringDataCassandraのリアクティブデータアクセス機能の使用方法を学習します。

特に、これはSpringDataCassandraの記事シリーズの3番目の記事です。 これでは、RESTAPIを使用してCassandraデータベースを公開します。

Spring Data Cassandraの詳細については、シリーズの最初のおよび2番目のの記事を参照してください。

2. Mavenの依存関係

実際のところ、SpringDataCassandraはProjectReactorとRxJavaリアクティブタイプをサポートしています。 このチュートリアルでは、プロジェクトリアクターのリアクティブタイプFluxおよびMonoを使用して説明します。

まず、チュートリアルに必要な依存関係を追加しましょう。

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-cassandra</artifactId>
    <version>2.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>io.projectreactor</groupId>
    <artifactId>reactor-core</artifactId>
</dependency>

spring-data-cassandra の最新バージョンは、ここにあります。

次に、RESTAPIを介してデータベースからSELECT操作を公開します。 それでは、RestControllerの依存関係も追加しましょう。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3. 私たちのアプリを実装する

データを永続化するので、最初にエンティティオブジェクトを定義しましょう。

@Table
public class Employee {
    @PrimaryKey
    private int id;
    private String name;
    private String address;
    private String email;
    private int age;
}

次に、作成する時間です EmployeeRepository から伸びる ReactiveCassandraRepository。 注意することが重要ですこのインターフェースにより、リアクティブタイプのサポートが可能になります s:

public interface EmployeeRepository extends ReactiveCassandraRepository<Employee, Integer> {
    @AllowFiltering
    Flux<Employee> findByAgeGreaterThan(int age);
}

3.1. CRUD操作用のRESTコントローラー

説明のために、単純なRESTコントローラーを使用したいくつかの基本的なSELECT操作を公開します。

@RestController
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @PostConstruct
    public void saveEmployees() {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(123, "John Doe", "Delaware", "[email protected]", 31));
        employees.add(new Employee(324, "Adam Smith", "North Carolina", "[email protected]", 43));
        employees.add(new Employee(355, "Kevin Dunner", "Virginia", "[email protected]", 24));
        employees.add(new Employee(643, "Mike Lauren", "New York", "[email protected]", 41));
        employeeService.initializeEmployees(employees);
    }

    @GetMapping("/list")
    public Flux<Employee> getAllEmployees() {
        Flux<Employee> employees = employeeService.getAllEmployees();
        return employees;
    }

    @GetMapping("/{id}")
    public Mono<Employee> getEmployeeById(@PathVariable int id) {
        return employeeService.getEmployeeById(id);
    }

    @GetMapping("/filterByAge/{age}")
    public Flux<Employee> getEmployeesFilterByAge(@PathVariable int age) {
        return employeeService.getEmployeesFilterByAge(age);
    }
}

最後に、簡単なEmployeeServiceを追加しましょう。

@Service
public class EmployeeService {

    @Autowired
    EmployeeRepository employeeRepository;

    public void initializeEmployees(List<Employee> employees) {
        Flux<Employee> savedEmployees = employeeRepository.saveAll(employees);
        savedEmployees.subscribe();
    }

    public Flux<Employee> getAllEmployees() {
        Flux<Employee> employees =  employeeRepository.findAll();
        return employees;
    }

    public Flux<Employee> getEmployeesFilterByAge(int age) {
        return employeeRepository.findByAgeGreaterThan(age);
    }

    public Mono<Employee> getEmployeeById(int id) {
        return employeeRepository.findById(id);
    }
}

3.2. データベース構成

次に、application.propertiesでCassandraとの接続に使用するキースペースとポートを指定しましょう。

spring.data.cassandra.keyspace-name=practice
spring.data.cassandra.port=9042
spring.data.cassandra.local-datacenter=datacenter1

注:datacenter1はデフォルトのデータセンター名です。

4. エンドポイントのテスト

最後に、APIエンドポイントをテストします。

4.1. 手動テスト

まず、データベースから従業員レコードをフェッチしましょう。

curl localhost:8080/employee/list

その結果、すべての従業員を獲得できます。

[
    {
        "id": 324,
        "name": "Adam Smith",
        "address": "North Carolina",
        "email": "[email protected]",
        "age": 43
    },
    {
        "id": 123,
        "name": "John Doe",
        "address": "Delaware",
        "email": "[email protected]",
        "age": 31
    },
    {
        "id": 355,
        "name": "Kevin Dunner",
        "address": "Virginia",
        "email": "[email protected]",
        "age": 24
    },
    {
        "id": 643,
        "name": "Mike Lauren",
        "address": "New York",
        "email": "[email protected]",
       "age": 41
    }
]

次に、IDで特定の従業員を見つけてみましょう。

curl localhost:8080/employee/643

その結果、Mr。 マイク・ローレンが戻ってきました:

{
    "id": 643,
    "name": "Mike Lauren",
    "address": "New York",
    "email": "[email protected]",
    "age": 41
}

最後に、年齢フィルターが機能するかどうかを見てみましょう。

curl localhost:8080/employee/filterByAge/35

そして予想通り、35歳以上のすべての従業員を取得します。

[
    {
        "id": 324,
        "name": "Adam Smith",
        "address": "North Carolina",
        "email": "[email protected]",
        "age": 43
    },
    {
        "id": 643,
        "name": "Mike Lauren",
        "address": "New York",
        "email": "[email protected]",
        "age": 41
    }
]

4.2. 統合テスト

さらに、テストケースを作成して、同じ機能をテストしてみましょう。

@RunWith(SpringRunner.class)
@SpringBootTest
public class ReactiveEmployeeRepositoryIntegrationTest {

    @Autowired
    EmployeeRepository repository;

    @Before
    public void setUp() {
        Flux<Employee> deleteAndInsert = repository.deleteAll()
          .thenMany(repository.saveAll(Flux.just(
            new Employee(111, "John Doe", "Delaware", "[email protected]", 31),
            new Employee(222, "Adam Smith", "North Carolina", "[email protected]", 43),
            new Employee(333, "Kevin Dunner", "Virginia", "[email protected]", 24),
            new Employee(444, "Mike Lauren", "New York", "[email protected]", 41))));

        StepVerifier
          .create(deleteAndInsert)
          .expectNextCount(4)
          .verifyComplete();
    }

    @Test
    public void givenRecordsAreInserted_whenDbIsQueried_thenShouldIncludeNewRecords() {
        Mono<Long> saveAndCount = repository.count()
          .doOnNext(System.out::println)
          .thenMany(repository
            .saveAll(Flux.just(
            new Employee(325, "Kim Jones", "Florida", "[email protected]", 42),
            new Employee(654, "Tom Moody", "New Hampshire", "[email protected]", 44))))
          .last()
          .flatMap(v -> repository.count())
          .doOnNext(System.out::println);

        StepVerifier
          .create(saveAndCount)
          .expectNext(6L)
          .verifyComplete();
    }

    @Test
    public void givenAgeForFilter_whenDbIsQueried_thenShouldReturnFilteredRecords() {
        StepVerifier
          .create(repository.findByAgeGreaterThan(35))
          .expectNextCount(2)
          .verifyComplete();
    }
}

5. 結論

要約すると、SpringDataCassandraを使用してリアクティブタイプを使用してノンブロッキングアプリケーションを構築する方法を学びました。

いつものように、GitHubでこのチュートリアルのソースコードを確認してください。