目录:

  • 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学习整理相关推荐

  1. 八个开源的 Spring Boot 学习资源,你值得拥有

    点击上方 好好学java ,选择 星标 公众号 重磅资讯.干货,第一时间送达 今日推荐:什么?你还在使用fastjson,性能太差了个人原创+1博客:点击前往,查看更多 转载自:牧马小子 Spring ...

  2. 15 个优秀开源的 Spring Boot 学习项目,一网打尽!

    Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...

  3. 超赞:不愧是阿里内部“Spring boot学习笔记”从头到尾,全是精华

    spring boot为何会出现? 随着动态语言的流行(Ruby.Groovy. Scala. Node.js),Java 的开发显得格外的笨重:繁多的配置.低下的开发效率.复杂的部署流程以及第三方技 ...

  4. 2023最新首发,全网最全 Spring Boot 学习宝典(附思维导图)

    作者:bug菌 博客:CSDN.掘金.infoQ.51CTO等 简介:CSDN/阿里云/华为云/51CTO博客专家,博客之星Top30,掘金年度人气作者Top40,51CTO年度博主Top12,掘金/ ...

  5. Spring Boot学习笔记-实践建言

    2019独角兽企业重金招聘Python工程师标准>>> 本文延续<Spring Boot学习笔记-快速示例>,从开发指南中摘出一些实践经验可供参考.这也是笔者看到的眼前一 ...

  6. Spring Boot学习笔记-进阶(3)

    文章目录 Spring Boot学习笔记-进阶(3) 一.Spring Boot与缓存 二.Spring Boot与消息 三.Spring Boot与检索 四.Spring Boot与任务 异步任务 ...

  7. Spring Boot学习笔记-基础(2)

    Spring Boot学习笔记-基础(2) Spring Boot 优点: – 快速创建独立运行的Spring项目以及与主流框架集成 – 使用嵌入式的Servlet容器,应用无需打成WAR包 – st ...

  8. Spring Boot学习笔记(1)

    文章目录 Spring Boot学习笔记(1) Spring Boot 整合 JSP Spring Boot HTML Thymeleaf 常用语法 Spring Boot 数据校验 Spring B ...

  9. Vue + Spring Boot 学习笔记02:引入数据库实现用户登录功能

    Vue + Spring Boot 学习笔记02:引入数据库实现用户登录功能 在学习笔记01里,我们利用跨域打通了前端的Vue与后端的Spring Boot,实现了用户登录功能,但是后台的登录控制器在 ...

最新文章

  1. miui通知栏要点两下_MIUI免费主题分享,半透明通知栏很好看,另附壁纸!
  2. 多个servlet配制方法
  3. c++中使用 hiredis/hiredis.h
  4. JQuery课堂学习笔记
  5. 五.几何对象和空间参考
  6. HomeBrew 更换为国内源--提高brew命令操作速度
  7. win8解决“telnet不是内部或外部命令”问题
  8. Hadoop学习记录(6)|Eclipse安装Hadoop 插件
  9. PermGen space 与 Java heap space
  10. wps linux 哪个版本好用吗,WPS Linux版与国产统一操作系统UOS完成适配:体验追上Wintel...
  11. 关于材料设计vector矢量图形
  12. 推荐几个优秀的微信小程序UI组件库
  13. mysql索引(三)聚集索引与非聚集索引(辅助索引)
  14. CodeFroces gym 100781 A.Adjoin the Networks(贪心)
  15. pytorch detach解析
  16. 对组件、模块、子系统、系统、框架、架构 定义浅析
  17. The APR based Apache Tomcat Native library which allows optimal performance in production
  18. vue项目 编辑器保存代码后自动更新浏览器页面内容
  19. Java爬虫初学——爬取BT电影天堂电影的磁力链接并筛选下载
  20. 2021-10-15 验证form表单的内容是否已存在数据库

热门文章

  1. vmware的vmdk格式虚拟机转换为kvm的qcow2格式
  2. 工业控制系统ICS网络安全简析
  3. 20165307《网络对抗技术》Exp1 PC平台逆向破解
  4. Python基础(三)文件操作和处理json
  5. springmvc + mybatis + ehcache + redis 分布式架构
  6. Unity3D之主角面朝方向一定区域内对象角度计算(转)
  7. SVN使用import导入新数据到版本库
  8. 删除vs的调试其他软件的功能
  9. Python基础:常用知识点汇总
  10. Windows 11 将使 AMD 芯片性能下降 15%!