由于只是一个小系统,ODPS的用户密码被写死在application.properties中
1.ODPS数据源注册
主要有2个方法:一个是CreateOdpsLink()这个方法主要是将odps连接的参数做初始化封装为Bean,供其他接口调用
二是OdpsExecSql:直接执行文本格式的sql语句
@Component
@Configuration
public class OdpsDatasourceConfiguration {
@Value("${my_access_id}")
private String my_access_id;
@Value("${my_access_key}")
private String my_access_key;
@Value("${odps_endpoint}")
private String odps_endpoint;
@Value("${odps_project}")
private String odps_project;
@Bean(name = "CreateOdpsLink")
public Odps CreateOdpsLink() throws Exception {
Account account = new AliyunAccount(my_access_id, my_access_key);
Odps odps = new Odps(account);
odps.setEndpoint(odps_endpoint);
odps.setDefaultProject(odps_project);
return odps;
}
public static List<Map> OdpsExecSql(Odps odps,String sql) throws Exception {
Instance i;
List<Map> list = new ArrayList<>();
i = SQLTask.run(odps, sql);
i.waitForSuccess();
List<Record> records = SQLTask.getResult(i);
for (Record record : records) {
int count = record.getColumnCount();
Column[] columns = record.getColumns();
Map<String, Object> map = new LinkedHashMap<>(16);
for (int i = 0; i < count; ++i) {
putByOdpsType(record, columns[i], map, i);
}
list.add(map);
}
return list;
}
private static void putByOdpsType(Record record, Column column, Map<String, Object> map, int i) {
switch (column.getTypeInfo().getOdpsType()) {
case BIGINT:
map.put(column.getName(), record.getBigint(i));
break;
case INT:
case TINYINT:
case SMALLINT:
map.put(column.getName(), Integer.valueOf((String)record.get(i)));
break;
}
}
}
2. Controller调用:
通过@Autowired的方式将Odps 实例中的参数进行调用;然后执行SQL语句
@RestController
@RequestMapping(path = "/datasource")
public class OdpsController {
@Autowired
@Qualifier("CreateOdpsLink")
private Odps odps;
@CrossOrigin
@RequestMapping(value = "/test", method = RequestMethod.GET)
private List<Map<String,String>> zero_link() throws Exception {
String input1 = "select * from a.a where ds = max_pt('a.a');";
Map <String,String> modelNew = new HashMap<String, String>();
List <Map<String,String>> List_model = new ArrayList<>();
List<Map> list = OdpsDatasourceConfiguration.OdpsExecSql(odps,input1);
for (Map map : list) {
List_model.add(modelNew);
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
modelNew.put(entry.getKey().toString(), entry.getValue().toString());
}
}
return List_model;
}
}
参考链接:
https://help.aliyun.com/document_detail/34614.html