无法将Spring Boot Java应用程序连接到Amazon Keyspaces。

huangapple go评论78阅读模式
英文:

unable to connect spring boot java application to amazon keyspaces

问题

这是配置类。

@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("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();
    }

}

实体类。

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

仓库类。

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> {
}

控制器类。

@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;
    }
}

主类。

@SpringBootApplication
@ComponentScan
public class DemoApplication {

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

}

出现连接 Amazon Keyspaces 错误的问题。

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.
英文:

This is the configuration class .

@Configuration
@PropertySource(value = { &quot;classpath:cassandra.properties&quot; })
@EnableCassandraRepositories(basePackages = { &quot;com.example.demo.repository&quot; })
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(&quot;cassandra.truststore.path&quot;));
InputStream is = new FileInputStream(&quot;D:/SampleProjects/spring-samples-master/restapi-cassandra/src/main/resources/cassandra_truststore.jks&quot;);
KeyStore keystore = KeyStore.getInstance(environment.getProperty(&quot;cassandra.truststore.type&quot;));
System.out.println(environment.getProperty(&quot;cassandra.truststore.password&quot;));
char[] pwd = environment.getProperty(&quot;cassandra.truststore.password&quot;).toCharArray();
keystore.load(is, pwd);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance(&quot;TLS&quot;);
sslContext.init(null, tm, null);
JdkSSLOptions sslOptions = JdkSSLOptions.builder().withSSLContext(sslContext).build();
cluster.setUsername(environment.getProperty(&quot;cassandra.username&quot;));
cluster.setPassword(environment.getProperty(&quot;cassandra.password&quot;));
cluster.setContactPoints(environment.getProperty(&quot;cassandra.contactpoints&quot;));
cluster.setPort(Integer.parseInt(environment.getProperty(&quot;cassandra.port&quot;)));
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(&quot;cassandra.keyspace&quot;);
}
@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&lt;Employee, String&gt; {
}

controller class

@RestController
public class EmployeeController
{
@Autowired
EmployeeRepository employeeRepository;
@GetMapping(value = &quot;/healthcheck&quot;, produces = &quot;application/json; charset=utf-8&quot;)
public String getHealthCheck()
{
return &quot;{ \&quot;isWorking\&quot; : true }&quot;;
}
@GetMapping(&quot;/employees&quot;)
public List&lt;Employee&gt; getEmployees()
{
Iterable&lt;Employee&gt; result = employeeRepository.findAll();
List&lt;Employee&gt; employeesList = new ArrayList&lt;Employee&gt;();
result.forEach(employeesList::add);
return employeesList;
}
@GetMapping(&quot;/employee/{id}&quot;)
public Optional&lt;Employee&gt; getEmployee(@PathVariable String id)
{
Optional&lt;Employee&gt; emp = employeeRepository.findById(id);
return emp;
}
@PutMapping(&quot;/employee/{id}&quot;)
public Optional&lt;Employee&gt; updateEmployee(@RequestBody Employee newEmployee, @PathVariable String id)
{
Optional&lt;Employee&gt; 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 = &quot;/employee/{id}&quot;, produces = &quot;application/json; charset=utf-8&quot;)
public String deleteEmployee(@PathVariable String id) {
Boolean result = employeeRepository.existsById(id);
employeeRepository.deleteById(id);
return &quot;{ \&quot;success\&quot; : &quot;+ (result ? &quot;true&quot; : &quot;false&quot;) +&quot; }&quot;;
}
@PostMapping(&quot;/employee&quot;)
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 .

答案1

得分: 1

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

英文:

Try setting the the local DC as us-east-1. I do not see it in your configuration.

huangapple
  • 本文由 发表于 2020年8月25日 22:12:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63580779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定