java-在使用DropWizard JDBI时使用自定义凭据

我正在使用Dropwizard JDBI框架开发Web服务.

现在,我不想使用yaml文件中的数据库配置,而是要使用“用户指定的参数”,而是通过端点url提供数据库配置.

>是否可以通过dropwizard jdbi获得自定义凭据?

如果是,在引用此代码时我应该考虑对代码进行哪些更改? ->

http://dropwizard.readthedocs.org/en/latest/manual/jdbi.html

我了解,在正常流程中,服务方法在run方法中获取配置详细信息-

-配置类

public class ExampleConfiguration extends Configuration {
    @Valid
    @NotNull
    @JsonProperty
    private DatabaseConfiguration database = new DatabaseConfiguration();

    public DatabaseConfiguration getDatabaseConfiguration() {
        return database;
    }
}

-服务等级

@Override
        public void run(ExampleConfiguration config,
                        Environment environment) throws ClassNotFoundException {
            final DBIFactory factory = new DBIFactory();
            final DBI jdbi = factory.build(environment, config.getDatabaseConfiguration(), "postgresql");
            final UserDAO dao = jdbi.onDemand(UserDAO.class);
            environment.addResource(new UserResource(dao));
        }

-和yaml

database:
  # the name of your JDBC driver
  driverClass: org.postgresql.Driver

  # the username
  user: pg-user

  # the password
  password: iAMs00perSecrEET

  # the JDBC URL
  url: jdbc:postgresql://db.example.com/db-prod

但是在这种情况下,我可能会在资源级别获得配置详细信息…

像-

@GET
@Path(value = "/getProduct/{Id}/{dbUrl}/{dbUname}/{dbPass}")
@Produces(MediaType.APPLICATION_JSON)
public Product getProductById(@PathParam(value = "Id") int Id,
        @PathParam(value = "dbUrl") String dbUrl,
        @PathParam(value = "dbUname") String dbUname,
        @PathParam(value = "dbPath") String dbPass) {

     //I have to connect to the DB here! using the params i have.         
     return new Product(); //should return the Product
}

如果有人能为我指明方向,我将不胜感激.

解决方法:

为什么不直接使用JDBI?

@GET
@Path(value = "/getProduct/{Id}/{dbUrl}/{dbUname}/{dbPass}")
@Produces(MediaType.APPLICATION_JSON)
public Product getProductById(@PathParam(value = "Id") int id,
    @PathParam(value = "dbUrl") String dbUrl,
    @PathParam(value = "dbUname") String dbUname,
    @PathParam(value = "dbPass") String dbPass) {
  DataSource ds = JdbcConnectionPool.create(dbUrl, dbUname, dbPass);
  DBI dbi = new DBI(ds);
  ProductDAO dao = dbi.open(ProductDao.class);
  Product product = dao.findById(id);
  dao.close();
  ds.dispose();
  return product;
}

@RegisterMapper(ProductMapper.class)
static interface ProductDao {
  @SqlQuery("select id from product_table where id = :id") // Whatever SQL query you need to product the product
  Product findById(@Bind("id") int id);

  @SqlQuery("select * from product_table")
  Iterator<Product> findAllProducts();
}

static class ProductMapper implements ResultSetMapper<Product> {
  public Product map(int index, ResultSet r, StatementContext ctx) throws SQLException {
    return new Product(r.getInt("id")); // Whatever product constructor you need
  }
}
上一篇:java-Dropwizard解压缩请求过滤器


下一篇:使用RDO Packstack在CentOS 8上安装OpenStack Victoria