物聯網架構成長之路(13)-SpringBoot入門
1. 前言
下載最新版的JavaEE eclipse-jee-oxygen-2-win32-x86_64.zip
安裝STS插件 Window->Eclipse Marketplace -> popular 下那個 Spring Tools(aka Spring IDE and Spring Tool Suite)
然後通過STS工具創建一個新的Spring boot工程,這裏就不細說了。網上資料很多,也比較簡單就可以搭建起來。後面對SpringBoot也只是簡單的提一下,還有說一下註意點。沒什麽好說的。我也是參考一些文檔和博客,自己玩玩而已。
大部分參考這系列博客,從頭到尾,調重點練習一遍: http://www.ityouknow.com/spring-boot.html
2. HelloWorld
後面入門Spring Cloud在進行細說,該系列博客主要是記錄我在搭建物聯網雲平臺時遇到的問題,和目前自己覺得最適合公司用的解決方案。
SpringApplicationDemo.java
1 @SpringBootApplication 2 public class SpringApplicationDemo { 3 @RequestMapping("/home") 4 String home() { 5 return "歡迎使用"; 6 } 7 public static voidmain(String[] args) { 8 System.out.println("start.."); 9 SpringApplication.run(SpringApplicationDemo.class, args); 10 } 11 }
pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>net.demo</groupId> 5 <artifactId>demo</artifactId> 6 <version>0.0.1-SNAPSHOT</version> 7 <name>demo Maven Webapp</name> 8 <url>http://maven.apache.org</url> 9 10 <parent> 11 <groupId>org.springframework.boot</groupId> 12 <artifactId>spring-boot-starter-parent</artifactId> 13 <version>1.5.9.RELEASE</version> 14 </parent> 15 <dependencies> 16 <dependency> 17 <groupId>org.springframework.boot</groupId> 18 <artifactId>spring-boot-starter-web</artifactId> 19 </dependency> 20 <dependency> 21 <groupId>org.springframework.boot</groupId> 22 <artifactId>spring-boot-devtools</artifactId> 23 <optional>true</optional> 24 </dependency> 25 <dependency> 26 <groupId>org.springframework.boot</groupId> 27 <artifactId>spring-boot-starter-test</artifactId> 28 </dependency> 29 </dependencies> 30 <build> 31 <plugins> 32 <plugin> 33 <groupId>org.springframework.boot</groupId> 34 <artifactId>spring-boot-maven-plugin</artifactId> 35 <configuration> 36 <fork>true</fork> 37 </configuration> 38 </plugin> 39 </plugins> 40 <finalName>demo</finalName> 41 </build> 42 <packaging>war</packaging> 43 </project>
3. 配置在application.properties
(1) 自定義Property
1 net.demo.title=\u6D4B\u8BD5\u4F8B\u5B50 2 net.demo.description=demo\u6D4B\u8BD5
引用
1 @Component 2 public class DemoProperties { 3 @Value("${net.demo.title}") 4 private String title; 5 @Value("${net.demo.description}") 6 private String description; 7 Get/Set 8 }
註入使用
1 @Autowired 2 DemoProperties prop;
(2)log配置
1 logging.path=log 2 logging.level.com.favorites=DEBUG 3 logging.level.org.springframework.web=INFO
4. 連接Postgres數據庫
pom.xml增加
1 <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql --> 2 <dependency> 3 <groupId>org.postgresql</groupId> 4 <artifactId>postgresql</artifactId> 5 </dependency> 6 <dependency> 7 <groupId>org.mybatis.spring.boot</groupId> 8 <artifactId>mybatis-spring-boot-starter</artifactId> 9 <version>1.1.1</version> 10 </dependency>
application.properties
1 net.demo.title=\u6D4B\u8BD5\u4F8B\u5B50 2 net.demo.description=demo\u6D4B\u8BD5 3 4 logging.path=log 5 logging.level.com.favorites=INFO 6 logging.level.org.springframework.web=INFO 7 8 spring.datasource.url=jdbc:postgresql://172.16.23.202:5432/test 9 spring.datasource.username=postgres 10 spring.datasource.password= 11 spring.datasource.driverClassName=org.postgresql.Driver 12 13 mybatis.typeAliasesPackage=net.xxx.demo.model 14 mybatis.mapperLocations=classpath:net/xxx/demo/mapper/*.xml
接下來就是跟以前SSM框架一樣了,
PersonMapper.xml
PersonModel.java
PersonDao.java
PersonService.java
PersonController.java
修改 mapper.xml Eclipse 可以安裝 MyBatipse 這個插件
5. thymeleaf 模版
這個只是拋磚引玉提一下而已,我估計不會用上。我後面準備考慮用阿裏的Ant.Design
6. Redis 連接
依賴 pom.xml
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-redis</artifactId> 4 </dependency>
配置 application.properties
1 # REDIS (RedisProperties) 2 spring.redis.database=0 3 spring.redis.host=172.16.20.229 4 spring.redis.port=6379 5 spring.redis.password= 6 spring.redis.pool.max-active=8 7 spring.redis.pool.max-wait=-1 8 spring.redis.pool.max-idle=8 9 spring.redis.pool.min-idle=0 10 spring.redis.timeout=0
RedisConfig.java
1 @Configuration 2 public class RedisConfig { 3 4 @Bean 5 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer(ObjectMapper objectMapper) { 6 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>( 7 Object.class); 8 jackson2JsonRedisSerializer.setObjectMapper(objectMapper); 9 return jackson2JsonRedisSerializer; 10 } 11 12 @Bean 13 RedisTemplate<String, Object> objRedisTemplate(JedisConnectionFactory connectionFactory, 14 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer) { 15 RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); 16 redisTemplate.setConnectionFactory(connectionFactory); 17 redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer); 18 StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); 19 redisTemplate.setKeySerializer(stringRedisSerializer); 20 redisTemplate.setHashKeySerializer(stringRedisSerializer); 21 return redisTemplate; 22 } 23 }
RedisTestService.java
1 @Service 2 public class RedisTestService { 3 4 @Autowired 5 private RedisTemplate<String, Object> redisTemplate; 6 7 private static String REDIS_TEST_KEY = "redis-test"; 8 9 public Person save(Person person) { 10 this.redisTemplate.opsForHash().put(REDIS_TEST_KEY, person.getName(), person); 11 return person; 12 } 13 14 public Object find(String uid) { 15 return this.redisTemplate.opsForHash().get(REDIS_TEST_KEY, uid); 16 } 17 18 public Map<Object, Object> findAll(){ 19 return this.redisTemplate.opsForHash().entries(REDIS_TEST_KEY); 20 } 21 22 public Long delete(String uid) { 23 return this.redisTemplate.opsForHash().delete(REDIS_TEST_KEY, uid); 24 } 25 }
RedisTestController.java
1 @RestController 2 @RequestMapping("/api/redis") 3 public class RedisTestController { 4 5 @Autowired 6 private RedisTestService redisTestService; 7 8 @RequestMapping("/save") 9 public Object save(@RequestParam("name") String name, 10 @RequestParam("password") String password, 11 @RequestParam("uid") Integer uid) { 12 Person person = new Person(); 13 person.setName(name); 14 person.setPassword(password); 15 person.setUid(uid); 16 return redisTestService.save(person); 17 } 18 19 @RequestMapping("/save1") 20 public Object save1(Person person) { 21 return redisTestService.save(person); 22 } 23 24 @GetMapping("{uid}") 25 public Object find(@PathVariable String uid) { 26 System.out.println(uid); 27 return redisTestService.find(uid); 28 } 29 30 @RequestMapping("/findall") 31 public Object findAll() { 32 return redisTestService.findAll(); 33 } 34 35 @GetMapping("/delete/{uid}") 36 public Long delete(@PathVariable String uid) { 37 return redisTestService.delete(uid); 38 } 39 }
7.Redis-Cache
1 @Configuration 2 @EnableCaching 3 public class RedisCacheManager { 4 5 @Bean 6 public RedisCacheManager cacheManager() { 7 RedisCacheManager redisCacheManager = new RedisCacheManager(); 8 return redisCacheManager; 9 } 10 }
然後可以通過如下註解進行緩存
1 @Cacheable(value="find", key="#uid")
如果發現Key相同,那麽直接返回redis裏的value,不對方法進行調用,否則調用對於方法,並設置到redis中。
參考這個 http://www.ityouknow.com/springboot/2016/03/06/springboot(%E4%B8%89)-Spring-Boot%E4%B8%ADRedis%E7%9A%84%E4%BD%BF%E7%94%A8.html
還有一個分布式session自帶解決方案 Session-spring-session-data-redis
https://segmentfault.com/a/1190000004358410
8. redis-session
pom.xml
1 <dependency> 2 <groupId>org.springframework.session</groupId> 3 <artifactId>spring-session-data-redis</artifactId> 4 </dependency>
SessionConfig.java
1 @Configuration 2 @EnableRedisHttpSession(maxInactiveIntervalInSeconds=5) 3 public class SessionConfig { 4 5 }
使用
1 @RequestMapping("/guid") 2 public String session(HttpSession session) { 3 UUID guid = (UUID)session.getAttribute("GUID"); 4 if(guid == null) { 5 guid = UUID.randomUUID(); 6 } 7 session.setAttribute("GUID", guid); 8 return session.getId(); 9 }
9. 定時器的使用
在application啟動類加上以下這個註解 @EnableScheduling 然後如下使用
1 @Scheduled(cron="*/5 * * * * ?") 2 private void process() { 3 System.out.println("this is scheduler task running: " + (count ++) + " " + System.currentTimeMillis()); 4 }
10.打包部署
根據pom.xml裏 <packaging>jar</packaging> 打成jar包或者war包
打成jar包
如果你使用的是maven來管理項目,執行以下命令既可以
1 cd 項目跟目錄(和pom.xml同級) 2 mvn clean package 3 ## 或者執行下面的命令 4 ## 排除測試代碼後進行打包 5 mvn clean package -Dmaven.test.skip=true
打包完成後jar包會生成到target目錄下,命名一般是 項目名+版本號.jar
啟動jar包命令
1 java -jar target/spring-boot-scheduler-1.0.0.jar
這種方式,只要控制臺關閉,服務就不能訪問了。下面我們使用在後臺運行的方式來啟動:
1 nohup java -jar target/spring-boot-scheduler-1.0.0.jar &
也可以在啟動的時候選擇讀取不同的配置文件
1 java -jar app.jar --spring.profiles.active=dev
也可以在啟動的時候設置jvm參數
1 java -Xms10m -Xmx80m -jar app.jar &
11.幾個常用插件
Vrapper 一個vim鍵盤映射插件
MyBatipse mybatis mapper插件
STS springboot插件
Decompiler 反編譯插件
物聯網架構成長之路(13)-SpringBoot入門