物联网架构成长之路(13)-SpringBoot入门
Posted 无脑仔的小明
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了物联网架构成长之路(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 void main(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入门的主要内容,如果未能解决你的问题,请参考以下文章
物联网架构成长之路(32)-SpringBoot集成MQTT客户端
物联网架构成长之路(59)-SpringBoot项目作为系统应用,自启动