物联网架构成长之路(13)-SpringBoot入门

时间:2022-06-05 17:21:33

1. 前言
  下载最新版的JavaEE eclipse-jee-oxygen-2-win32-x86_64.zip
  安装STS插件 Window->Eclipse Marketplace -> popular 下那个 Spring Tools(aka Spring IDE and Spring Tool Suite)
物联网架构成长之路(13)-SpringBoot入门
  然后通过STS工具创建一个新的Spring boot工程,这里就不细说了。网上资料很多,也比较简单就可以搭建起来。后面对SpringBoot也只是简单的提一下,还有说一下注意点。没什么好说的。我也是参考一些文档和博客,自己玩玩而已。
  大部分参考这系列博客,从头到尾,调重点练习一遍: http://www.ityouknow.com/spring-boot.html
2. HelloWorld
  后面入门Spring Cloud在进行细说,该系列博客主要是记录我在搭建物联网云平台时遇到的问题,和目前自己觉得最适合公司用的解决方案。
  SpringApplicationDemo.java

 @SpringBootApplication
public class SpringApplicationDemo {
@RequestMapping("/home")
String home() {
return "欢迎使用";
}
public static void main(String[] args) {
System.out.println("start..");
SpringApplication.run(SpringApplicationDemo.class, args);
}
}

  pom.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo Maven Webapp</name>
<url>http://maven.apache.org</url> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
<finalName>demo</finalName>
</build>
<packaging>war</packaging>
</project>

  3. 配置在application.properties

  (1) 自定义Property

 net.demo.title=\u6D4B\u8BD5\u4F8B\u5B50
net.demo.description=demo\u6D4B\u8BD5

  引用

 @Component
public class DemoProperties {
@Value("${net.demo.title}")
private String title;
@Value("${net.demo.description}")
private String description;
Get/Set
}

  注入使用

 @Autowired
DemoProperties prop;

  (2)log配置

 logging.path=log
logging.level.com.favorites=DEBUG
logging.level.org.springframework.web=INFO

4. 连接Postgres数据库

  pom.xml增加

 <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>

  application.properties

 net.demo.title=\u6D4B\u8BD5\u4F8B\u5B50
net.demo.description=demo\u6D4B\u8BD5 logging.path=log
logging.level.com.favorites=INFO
logging.level.org.springframework.web=INFO spring.datasource.url=jdbc:postgresql://172.16.23.202:5432/test
spring.datasource.username=postgres
spring.datasource.password=
spring.datasource.driverClassName=org.postgresql.Driver mybatis.typeAliasesPackage=net.xxx.demo.model
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

 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

  配置 application.properties

 # REDIS (RedisProperties)
spring.redis.database=
spring.redis.host=172.16.20.229
spring.redis.port=
spring.redis.password=
spring.redis.pool.max-active=
spring.redis.pool.max-wait=-
spring.redis.pool.max-idle=
spring.redis.pool.min-idle=
spring.redis.timeout=

  RedisConfig.java

 @Configuration
public class RedisConfig { @Bean
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer(ObjectMapper objectMapper) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
Object.class);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
return jackson2JsonRedisSerializer;
} @Bean
RedisTemplate<String, Object> objRedisTemplate(JedisConnectionFactory connectionFactory,
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
return redisTemplate;
}
}

  RedisTestService.java

 @Service
public class RedisTestService { @Autowired
private RedisTemplate<String, Object> redisTemplate; private static String REDIS_TEST_KEY = "redis-test"; public Person save(Person person) {
this.redisTemplate.opsForHash().put(REDIS_TEST_KEY, person.getName(), person);
return person;
} public Object find(String uid) {
return this.redisTemplate.opsForHash().get(REDIS_TEST_KEY, uid);
} public Map<Object, Object> findAll(){
return this.redisTemplate.opsForHash().entries(REDIS_TEST_KEY);
} public Long delete(String uid) {
return this.redisTemplate.opsForHash().delete(REDIS_TEST_KEY, uid);
}
}

  RedisTestController.java

 @RestController
@RequestMapping("/api/redis")
public class RedisTestController { @Autowired
private RedisTestService redisTestService; @RequestMapping("/save")
public Object save(@RequestParam("name") String name,
@RequestParam("password") String password,
@RequestParam("uid") Integer uid) {
Person person = new Person();
person.setName(name);
person.setPassword(password);
person.setUid(uid);
return redisTestService.save(person);
} @RequestMapping("/save1")
public Object save1(Person person) {
return redisTestService.save(person);
} @GetMapping("{uid}")
public Object find(@PathVariable String uid) {
System.out.println(uid);
return redisTestService.find(uid);
} @RequestMapping("/findall")
public Object findAll() {
return redisTestService.findAll();
} @GetMapping("/delete/{uid}")
public Long delete(@PathVariable String uid) {
return redisTestService.delete(uid);
}
}

7.Redis-Cache

 @Configuration
@EnableCaching
public class RedisCacheManager { @Bean
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
return redisCacheManager;
}
}

  然后可以通过如下注解进行缓存

 @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

 <dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>

  SessionConfig.java

 @Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=5)
public class SessionConfig { }

  使用

 @RequestMapping("/guid")
public String session(HttpSession session) {
UUID guid = (UUID)session.getAttribute("GUID");
if(guid == null) {
guid = UUID.randomUUID();
}
session.setAttribute("GUID", guid);
return session.getId();
}

物联网架构成长之路(13)-SpringBoot入门

9. 定时器的使用
  在application启动类加上以下这个注解 @EnableScheduling   然后如下使用

 @Scheduled(cron="*/5 * * * * ?")
private void process() {
System.out.println("this is scheduler task running: " + (count ++) + " " + System.currentTimeMillis());
}

10.打包部署

  根据pom.xml里   <packaging>jar</packaging> 打成jar包或者war包
  打成jar包
  如果你使用的是maven来管理项目,执行以下命令既可以

 cd 项目跟目录(和pom.xml同级)
mvn clean package
## 或者执行下面的命令
## 排除测试代码后进行打包
mvn clean package -Dmaven.test.skip=true

  打包完成后jar包会生成到target目录下,命名一般是 项目名+版本号.jar

  启动jar包命令

 java -jar target/spring-boot-scheduler-1.0..jar

  这种方式,只要控制台关闭,服务就不能访问了。下面我们使用在后台运行的方式来启动:

 nohup java -jar target/spring-boot-scheduler-1.0..jar &

  也可以在启动的时候选择读取不同的配置文件

 java -jar app.jar --spring.profiles.active=dev

  也可以在启动的时候设置jvm参数

 java -Xms10m -Xmx80m -jar app.jar &

11.几个常用插件

  Vrapper 一个vim键盘映射插件
  MyBatipse mybatis mapper插件
  STS springboot插件
  Decompiler  反编译插件