小工具知识网

当前位置: 首页 > 行业知识 > springboot 安装指南

行业知识

springboot 安装指南

2026-12-06 21:10:34 来源:互联网转载

目录

1、创建springboot工程(idea)

首先需要安装idea,然后选择新建工程。

 选择Spring boot Maven项目,并使用java8, Springboot 3.0就默认使用java17

创建2个模款 saas-web和saas-dao

在pom.xml中引入 mysql 和 mybatis-plus

创建数据表user

在saas-dao模款中创建实体类

在saas-dao模块中创建mapper

在saas-web中创建控制器

2、安装nacos组件

需要先安装nacos 2.0.3

在pom.xml中增加如下 代码

在resources目录中新建bootstrap.yml 并编写内容

在saas-web中创建启动类WebApp

3、集成数据库连接池

4、安装springboot-redis

1、创建saas-cache模块。

2、安装redis依赖

3、在nacos编写application.properties

4、编写配置类

5、编写注解缓存类

5、启动springboot


1、创建springboot工程(idea)

首先需要安装idea,然后选择新建工程。

 

 选择Spring boot Maven项目,并使用java8, Springboot 3.0就默认使用java17

工程建好后,修改pom.xml中 springboot的版本,用来匹配后续nacos的使用。

修改springboot 版本为2.3.2.RELEASE。

创建2个模款 saas-web和saas-dao

在pom.xml中引入 mysql 和 mybatis-plus

mybatis-plus 文档

                    com.baomidou            mybatis-plus-boot-starter            3.4.3.4                            mysql            mysql-connector-java            5.1.46        

创建数据表user

CREATE TABLE `user` (  `id` bigint(20) unsigned NOT NULL,  `country` varchar(45) NOT NULL DEFAULT '' COMMENT '国家',  `mobile` varchar(12) NOT NULL COMMENT '手机号码',  `password` varchar(32) DEFAULT NULL COMMENT '用户密码',  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '用户状态',  `created_at` int(11) DEFAULT NULL COMMENT '创建日期',  `updated_at` int(11) DEFAULT NULL COMMENT '更新日期',  `salt` varchar(16) DEFAULT NULL COMMENT '密码盐',  PRIMARY KEY (`id`),  UNIQUE KEY `idx_mobile` (`mobile`,`country`) USING BTREE COMMENT '''手机号码''',  KEY `idx_created_at` (`created_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';

在saas-dao模款中创建实体类

package com.xxx.saas.entity.user;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableId;import com.baomidou.mybatisplus.annotation.TableName;import lombok.Data;@TableName("user")@Datapublic class User {    @TableId(type = IdType.ASSIGN_ID)    private Long id;    private String country;    private String mobile;    private String password;    private Short status;    @TableField("created_at")    private Integer createdAt;    @TableField("updated_at")    private Integer updatedAt;    private String salt;}

在saas-dao模块中创建mapper

package com.xxx.saas.mapper.user;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.xxx.saas.entity.user.User;import javax.annotation.Resource;@Resourcepublic interface UserMapper extends BaseMapper {}

在saas-web中创建控制器

package com.xxx.saas.controller.user;import com.xxx.saas.cache.user.UserCache;import com.xxx.saas.entity.user.User;import com.xxx.saas.mapper.user.UserMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/")public class UserController {    @Autowired    private UserMapper userMapper;    @Autowired    private UserCache userCache;    @GetMapping("index")    public User getList()    {        User users = userCache.getUser("138388711962");        return users;    }    @GetMapping("delete")    public String deleteUser()    {        userCache.deleteUser("138388711962");        return "success";    }}

2、安装nacos组件

需要先安装nacos 2.0.3

nacos服务端下载
nacos配置 (转载)

在pom.xml中增加如下 代码

                    com.alibaba.cloud            spring-cloud-starter-alibaba-nacos-config            2.2.6.RELEASE        

 注意:不能使用原来的application.yml作为配置文件,而是新建一个bootstrap.yml作为配置文件

配置文件优先级(由高到低):
bootstrap.properties > bootstrap.yml > application.properties > application.yml

在resources目录中新建bootstrap.yml 并编写内容

spring:  application:    name: xxx-ucenter #配置名称  cloud:    nacos:      config:        server-addr: 1.11.111.1:8088 #nacos服务器地址        group: DEFAULT_GROUP    #默认分组        namespace: xxx-dc    #命名空间        file-extension: properties #扩展类型        refresh-enabled: true

在saas-web中创建启动类WebApp

package com.xxx.saas;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication(scanBasePackages = {"com.xxx.*"})@MapperScan("com.xxx.saas.mapper")public class WebApp {    public static void main(String[] args) {        SpringApplication.run(WebApp.class, args);    }}

3、集成数据库连接池

alibaba-druid连接池(转载)

在nacos配置文件中配置

server.port=8080spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.druid.url=jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=UTF-8&?useUnicode=truespring.datasource.druid.username=rootspring.datasource.druid.password=rootspring.datasource.druid.max-active=100spring.datasource.druid.initial-size=10spring.datasource.druid.min-idle=5spring.datasource.druid.min-evictable-idle-time-millis=300000spring.datasource.druid.max-wait=60000spring.datasource.druid.validation-query=select 1spring.datasource.druid.test-on-borrow=truespring.datasource.druid.test-on-return=truespring.datasource.druid.test-while-idle=truespring.datasource.druid.time-between-connect-error-millis=60000mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4、安装springboot-redis

springboot集成redis使用注解缓存(转载)

1、创建saas-cache模块。

 

2、安装redis依赖

                    org.springframework.boot            spring-boot-starter-data-redis                            org.apache.commons            commons-pool2            2.6.2        

3、在nacos编写application.properties

spring.redis.host=11.111.34.211spring.redis.port=6379spring.redis.database=0spring.redis.password=rootspring.redis.lettuce.pool.max-active=100spring.redis.lettuce.pool.max-wait=1spring.redis.lettuce.pool.max-idle=10spring.redis.lettuce.pool.min-idle=0spring.redis.timeout=5000

4、编写配置类

package com.xxx.saas.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;@Configurationpublic class RedisConfig extends CachingConfigurerSupport {    @Bean    public RedisTemplate redisTemplate(RedisConnectionFactory factory)    {        RedisTemplate template = new RedisTemplate();        RedisSerializer redisSerializer = new StringRedisSerializer();        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new                Jackson2JsonRedisSerializer(Object.class);        ObjectMapper om = new ObjectMapper();        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);        jackson2JsonRedisSerializer.setObjectMapper(om);        template.setConnectionFactory(factory);        //key序列化方式        template.setKeySerializer(redisSerializer);        //value序列化        template.setValueSerializer(jackson2JsonRedisSerializer);        //value hashmap序列化        template.setHashValueSerializer(jackson2JsonRedisSerializer);        return template;    }    @Bean    public CacheManager cacheManager(RedisConnectionFactory factory) {        RedisSerializer redisSerializer = new StringRedisSerializer();        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new                Jackson2JsonRedisSerializer(Object.class);        //解决查询缓存转换异常的问题        ObjectMapper om = new ObjectMapper();        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);        jackson2JsonRedisSerializer.setObjectMapper(om);        // 配置序列化(解决乱码的问题),过期时间600秒        RedisCacheConfiguration config =                RedisCacheConfiguration.defaultCacheConfig()                        .entryTtl(Duration.ofSeconds(600))                        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))                        .disableCachingNullValues();        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)                .cacheDefaults(config)                .build();        return cacheManager;    }}

5、编写注解缓存类

package com.xxx.saas.cache.user;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.xxx.saas.entity.user.User;import com.xxx.saas.mapper.user.UserMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Component;@Componentpublic class UserCache {    @Autowired    private UserMapper userMapper;        //生成缓存    @Cacheable(key = "#mobile", cacheNames = "user")    public User getUser(String mobile)    {        QueryWrapper oneUser = new QueryWrapper();        oneUser.eq("mobile", mobile);        return userMapper.selectOne(oneUser);    }        //删除缓存    @CacheEvict(key = "#mobile", cacheNames = "user")    public void deleteUser(String mobile)    {    }}

5、启动springboot

2022-03-02 17:44:53.745  INFO 12331 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8089 (http)2022-03-02 17:44:53.750  INFO 12331 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]2022-03-02 17:44:53.750  INFO 12331 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.37]2022-03-02 17:44:53.785  INFO 12331 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext2022-03-02 17:44:53.785  INFO 12331 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 459 msLogging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.2022-03-02 17:44:53.856  INFO 12331 --- [  restartedMain] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource2022-03-02 17:44:55.119  INFO 12331 --- [  restartedMain] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited

表示端口已经启动。

访问网站:

返回数据:http://127.0.0.1:8089/index

删除缓存:http://127.0.0.1:8089/delete

注:部分资源转载于网络,如有侵权,请联系本人,即刻删除。

上一篇:服务器失灵怎么办?

下一篇:pr服务器断开怎么解决?