javascript
Spring boot学习整理
目錄:
- Springboot結合hbase
- Springboot結合elasticsearch
- Springboot結合RestTemplate處理Http請求
- Springboot的maven相關
- Springboot結合dubbox
- Springboot的banner設定
- Springboot結合Kafka
?
?
Springboot結合hbase
首先在pom中添加依賴
<dependency><groupId>org.apache.hbase</groupId><artifactId>hbase-client</artifactId><version>1.2.0</version><exclusions><exclusion><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId></exclusion><exclusion><groupId>org.mortbay.jetty</groupId><artifactId>servlet-api-2.5</artifactId></exclusion><exclusion><groupId>org.mortbay.jetty</groupId><artifactId>servlet-api-2.5-6.1.14</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-hdfs</artifactId><version>2.6.0</version><exclusions><exclusion><artifactId>servlet-api</artifactId><groupId>javax.servlet</groupId></exclusion></exclusions></dependency>?
代碼:
@Autowiredpublic SearchDaoImpl(AppSettings appSettings){this.appSettings = appSettings;Configuration HBASE_CONFIG = new Configuration();//與hbase/conf/hbase-site.xml中hbase.zookeeper.quorum配置的值相同HBASE_CONFIG.set("hbase.zookeeper.quorum", appSettings.getHbasename());//與hbase/conf/hbase-site.xml中hbase.zookeeper.property.clientPort配置的值相同HBASE_CONFIG.set("hbase.zookeeper.property.clientPort", appSettings.getHbaseport());conf = HBaseConfiguration.create(HBASE_CONFIG);}?
?
?
Springboot結合elasticsearch
1.maven設置
springboot的版本是1.5.1.RELEASE。這個版本springboot使用的ES版本是2.4.4,其依賴的guava是16.0.1
這里我們需要手動指定guava為18.0版本,否則會出現異常?java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concu?rrent/Executor
...<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-elasticsearch</artifactId></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>18.0</version></dependency>....?
2.修改配置,在application.properties中添加以下內容
########### es setting ########### spring.data.elasticsearch.cluster-name=yq-cluster spring.data.elasticsearch.cluster-nodes=node3.test.cn:9300,node4.test.cn:9300,node5.test.cn:9300 spring.data.elasticsearch.local=false spring.data.elasticsearch.repositories.enabled=true?
3.創建實體類(與ES中存儲的內容格式對應)
package com.product;import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document;@Document(indexName = "yuqing", type = "emp", shards = 3, replicas = 1, refreshInterval = "-1") public class MyClient {@Idprivate String id;private String first_name;private String last_name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getFirst_name() {return first_name;}public void setFirst_name(String first_name) {this.first_name = first_name;}public String getLast_name() {return last_name;}public void setLast_name(String last_name) {this.last_name = last_name;}}?
4.建立資源庫
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;public interface ClientRepository extends ElasticsearchRepository<MyClient, String> {}?
5.服務接口
public interface EsService {MyClient findClient(String id); }?
6.服務實現
import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;@Service public class EsServiceImpl implements EsService {@Autowiredprivate ClientRepository clientDao;private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(EsServiceImpl.class);public MyClient findClient(String id) {MyClient client = clientDao.findOne(id);LOG.info(" get cliente by id {} is {}", id, client);return client;} }?
7.應用
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;@RestController @RequestMapping(value = "/es/") public class EsController {@Autowiredprivate EsService esl;@RequestMapping(value = "test", method = RequestMethod.POST)public Object test(@RequestBody String id) {return esl.findClient(id);} }?
參考:Spring boot + elasticsearch的最簡單實踐
在實際使用中要注意,安裝的es版本與springboot中引用的es版本不能有差異不能太大。
例如安裝的是2.4.2的,那么api使用的2.4.x基本沒問題,但如果引用5.x以上那肯定就不行了,會提示?None of the configured nodes are available
所以使用時要先看一下當前?spring-data-elasticsearch 所使用的es版本
?
Springboot結合RestTemplate處理Http請求
先定義config bean
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate;@Configuration public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory factory) {return new RestTemplate(factory);}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory() {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(5000);// msfactory.setConnectTimeout(15000);// msreturn factory;} }?
?
應用
注:針對返回結果的序列化問題,目前沒有找到方便快捷的方式,只好通過Object轉HashMap的途徑解決(雖然這種方法在屬性多的情況下也比較復雜)
RestTemplate.getForObject雖然可以指定為業務類,但是轉換始終有問題。
@RestController @EnableAutoConfiguration @Import(value = { RestTemplateConfig.class }) public class SpringRestTemplateApp {@AutowiredRestTemplate restTemplate;/*********** HTTP GET method *************/@RequestMapping("")public String hello() {String url = "http://localhost:8081/user"; HashMap<String,Object> user = (HashMap<String,Object>)restTemplate.getForObject(url, Object.class); return user.get("name").toString();}@RequestMapping("/user")public User genUser() {User user = new User();user.setAge(18);user.setName("Ray");return user;}public class User {private int age;private String name;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}}public static void main(String[] args) throws Exception {SpringApplication.run(SpringRestTemplateApp.class, args);} }?
如果想將返回結果轉換為實體對象(比如前面代碼中的User),需要以字符串接收結果,然后再轉換為對象。
不過java的json工具(我用的jackson)貌似不是很給力,也或許是我使用不當,總感覺比C#的差多了,轉換個json都好麻煩,尤其是復雜對象的時候(嵌套多層類,并且有List)
先定義實體類,這里要注意的是,如果有嵌套的類,必須要定義為靜態類
public class Company {@JsonIgnoreProperties(ignoreUnknown=true)public static class Employee {public Employee () {}private String name;public String getName() {return name;}public void setName(String name) {this.name= name;}}public Company () {}private List<Employee> emps;public List<Employee> getEmployees() {return emps;}public void setEmployees(List<Employee> Employees) {this.emps= Employees;} }?
轉換
public class TransferTest {private static TransferTest instance;public static TransferTest instance() {if (instance == null) {instance = new TransferTest();}return instance;}public TransferTest() {//只需要定義一次objectMapper = new ObjectMapper() {private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper();public <T> T readValue(String value, Class<T> valueType) {try {return jacksonObjectMapper.readValue(value, valueType);} catch (IOException e) {throw new RuntimeException(e);}}public String writeValue(Object value) {try {return jacksonObjectMapper.writeValueAsString(value);} catch (Exception e) {throw new RuntimeException(e);}}};}private Company doTransfer(String origin, String from, String to) throws UnirestException {String resp = restTemplate.getForObject(<url>,<data>,String.Class); //使用某種http工具類以字符串獲取返回結果Company data = objectMapper.readValue(str, Company.class);return data ;} }
?
?
真的感覺好麻煩/(ㄒoㄒ)/~~
?
?
?
Springboot的maven相關
在將springboot項目發布的時候我們都是用maven打包成jar包,然后使用 ?java -jar xxx.jar ?直接啟動
但是有時候發現執行之后會提示找不到啟動程序。
解決方法:在pom文件中添加以下內容
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>1.5.2.RELEASE</version><executions><execution><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>?
Springboot的banner設定
Springboot的banner很容易設置,只需要將banner.txt文件加到 src/main/resources 目錄下即可
?
這里給出一個碼農保護神
${AnsiColor.BRIGHT_YELLOW} // _ooOoo_ // // o8888888o // // 88" . "88 // // (| ^_^ |) // // O\ = /O // // ____/`---'\____ // // .' \\| |// `. // // / \\||| : |||// \ // // / _||||| -:- |||||- \ // // | | \\\ - /// | | // // | \_| ''\---/'' | | // // \ .-\__ `-` ___/-. / // // ___`. .' /--.--\ `. . ___ // // ."" '< `.___\_<|>_/___.' >'"". // // | | : `- \`.;`\ _ /`;.`/ - ` : | | // // \ \ `-. \_ __\ /__ _/ .-` / / // // ========`-.____`-.___\_____/___.-`____.-'======== // // `=---=' // // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // // 佛祖保佑 永不宕機 永無BUG // ${AnsiColor.BRIGHT_RED} Application Version: ${application.version}${application.formatted-version} Spring Boot Version: ${spring-boot.version}${spring-boot.formatted-version}參考:https://blog.csdn.net/baochanghong/article/details/54286422?
?
轉載于:https://www.cnblogs.com/TiestoRay/p/6526448.html
總結
以上是生活随笔為你收集整理的Spring boot学习整理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 尴尬:原来java中有两个 ModelA
- 下一篇: 树莓派:文本编辑器与文件