cassandra 无法将spring Boot java应用程序连接到amazon密钥空间

vh0rcniy  于 2022-11-05  发布在  Cassandra
关注(0)|答案(1)|浏览(137)

This is the configuration class .

@Configuration
@PropertySource(value = { "classpath:cassandra.properties" })
@EnableCassandraRepositories(basePackages = { "com.example.demo.repository" })
public class CassnadraConfig extends AbstractCassandraConfiguration {

    private static final Logger LOG = LoggerFactory.getLogger(CassnadraConfig.class);

    @Autowired
    private Environment environment;

    @Bean
    @Override
    public CassandraClusterFactoryBean cluster() {
         final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
         try {
            PoolingOptions poolingOptions = new PoolingOptions();
            poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, 10);
            poolingOptions.setPoolTimeoutMillis(5000);
            poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, 10);
        //  InputStream is = new FileInputStream(environment.getProperty("cassandra.truststore.path"));
            InputStream is = new FileInputStream("D:/SampleProjects/spring-samples-master/restapi-cassandra/src/main/resources/cassandra_truststore.jks");
            KeyStore keystore = KeyStore.getInstance(environment.getProperty("cassandra.truststore.type"));
            System.out.println(environment.getProperty("cassandra.truststore.password"));
            char[] pwd = environment.getProperty("cassandra.truststore.password").toCharArray();
            
            keystore.load(is, pwd);

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keystore);
            TrustManager[] tm = tmf.getTrustManagers();
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tm, null);

            JdkSSLOptions sslOptions = JdkSSLOptions.builder().withSSLContext(sslContext).build();
            cluster.setUsername(environment.getProperty("cassandra.username"));
            cluster.setPassword(environment.getProperty("cassandra.password"));
            cluster.setContactPoints(environment.getProperty("cassandra.contactpoints"));
            cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port")));
            cluster.setSslEnabled(true);
            cluster.setSslOptions(sslOptions);
            cluster.setPoolingOptions(poolingOptions);
         }
         catch(Exception ex) {
             System.out.println(ex);
         }
        return cluster;
    
    }

    @Override
    protected String getKeyspaceName() {
        return environment.getProperty("cassandra.keyspace");
    }

    @Override
    @Bean
    public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
        return new BasicCassandraMappingContext();
    }

}

Entity class

@AllArgsConstructor
@Getter @Setter
@Table
public class Employee {
    @PrimaryKey 
    private @NonNull String id;
    private @NonNull String firstName;
    private @NonNull String lastName;
    private @NonNull String email;
}

Repository class
package com.example.demo.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.model.Employee;

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, String> {
}

controller class

@RestController
public class EmployeeController
{
    @Autowired
    EmployeeRepository employeeRepository;

    @GetMapping(value = "/healthcheck", produces = "application/json; charset=utf-8")
    public String getHealthCheck()
    {
        return "{ \"isWorking\" : true }";
    }

    @GetMapping("/employees")
    public List<Employee> getEmployees()
    {
        Iterable<Employee> result = employeeRepository.findAll();
        List<Employee> employeesList = new ArrayList<Employee>();
        result.forEach(employeesList::add);
        return employeesList;
    }

    @GetMapping("/employee/{id}")
    public Optional<Employee> getEmployee(@PathVariable String id)
    {
        Optional<Employee> emp = employeeRepository.findById(id);
        return emp;
    }

    @PutMapping("/employee/{id}")
    public Optional<Employee> updateEmployee(@RequestBody Employee newEmployee, @PathVariable String id)
    {
        Optional<Employee> optionalEmp = employeeRepository.findById(id);
        if (optionalEmp.isPresent()) {
            Employee emp = optionalEmp.get();
            emp.setFirstName(newEmployee.getFirstName());
            emp.setLastName(newEmployee.getLastName());
            emp.setEmail(newEmployee.getEmail());
            employeeRepository.save(emp);
        }
        return optionalEmp;
    }

    @DeleteMapping(value = "/employee/{id}", produces = "application/json; charset=utf-8")
    public String deleteEmployee(@PathVariable String id) {
        Boolean result = employeeRepository.existsById(id);
        employeeRepository.deleteById(id);
        return "{ \"success\" : "+ (result ? "true" : "false") +" }";
    }

    @PostMapping("/employee")
    public Employee addEmployee(@RequestBody Employee newEmployee)
    {
        String id = String.valueOf(new Random().nextInt());
        Employee emp = new Employee(id, newEmployee.getFirstName(), newEmployee.getLastName(), newEmployee.getEmail());
        employeeRepository.save(emp);
        return emp;
    }
}

main class

@SpringBootApplication
@ComponentScan
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
        
    }

}

I am not able to connect to amazon keyspaces ,getting error
Caused by: java.lang.IllegalArgumentException: Failed to add contact point: cassandra.us-east-1.amazonaws.com at com.datastax.driver.core.Cluster$Builder.addContactPoint(Cluster.java:922) ~[cassandra-driver-core-3.6.0.jar:na] at com.datastax.driver.core.Cluster$Builder.addContactPoints(Cluster.java:942) ~[cassandra-driver-core-3.6.0.jar:na] at org.springframework.data.cassandra.config.CassandraClusterFactoryBean.afterPropertiesSet(CassandraClusterFactoryBean.java:174) ~[spring-data-cassandra-2.1.4.RELEASE.jar:2.1.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE] ... 111 common frames omitted **Caused by: java.net.UnknownHostException: cassandra.us-east-1.amazonaws.com**
Any idea please share it .

vxf3dgd4

vxf3dgd41#

尝试将本地DC设置为us-east-1。我在您的配置中没有看到它。

相关问题