SpringBoot

2023-05-16

  • resources/application.properties:Spring Boot应用的配置文件;可以修改一些默认设置;

server.port=8081   //改变默认端口号

  • 使用SpringMVC

配置thymeleaf

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

在login.html,dashboard.html等中配置th的css,src等静态资源,否则无法加载

 <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/wbjars/jquery/3.3.3/jquery.js}"></script>
		<script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/webjars/popper.js/1.11.1/dist/popper.js}"></script>
		<script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script>

		<!-- Icons -->
		<script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{asserts/js/feather.min.js}"></script>
		<script>
  • 使用JPA

1.使用JPA配置映射关系

@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //指定和哪个数据表对应;如果省略默认表名是user
public class User {

    @Id //这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    private Integer id;

    @Column(name = "last_name", length = 50) //这是和数据表对应的一个列
    private String lastName;

    @Column //省略默认列名就是属性名
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

2.继承Jpa仓库的方法

public interface UserRepository extends JpaRepository<User,Integer> {
}

3.application.yml里面配置jpa

  jpa:
#    更新或者创建数据表结构
    hibernate:
      ddl-auto: update
#    控制台显示SQL
    show-sql: true
  • cache与springboot的整合

不用redis,则cache默认使用concurrenthashmap存储


@EnableCaching
@MapperScan("com.atguigu.cache.mapper")
@SpringBootApplication
public class SpringBoot01CacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot01CacheApplication.class, args);
    }

}
@CacheConfig(cacheNames="emp"/*,cacheManager = "employeeCacheManager"*/) //抽取缓存的公共配置
@Service
public class EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    /**
     * 将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法;
     * CacheManager管理多个Cache组件的,对缓存的真正CRUD操作在Cache组件中,每一个缓存组件有自己唯一一个名字;
     *

     *
     * 原理:
     *   1、自动配置类;CacheAutoConfiguration
     *   2、缓存的配置类
     *   org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration【默认】
     *   org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
     *   3、哪个配置类默认生效:SimpleCacheConfiguration;
     *
     *   4、给容器中注册了一个CacheManager:ConcurrentMapCacheManager
     *   5、可以获取和创建ConcurrentMapCache类型的缓存组件;他的作用将数据保存在ConcurrentMap中;
     *
     *   运行流程:
     *   @Cacheable:
     *   1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
     *      (CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
     *   2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
     *      key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key;
     *          SimpleKeyGenerator生成key的默认策略;
     *                  如果没有参数;key=new SimpleKey();
     *                  如果有一个参数:key=参数的值
     *                  如果有多个参数:key=new SimpleKey(params);
     *   3、没有查到缓存就调用目标方法;
     *   4、将目标方法返回的结果,放进缓存中
     *
     *   @Cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
     *   如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
     *
     *   核心:
     *      1)、使用CacheManager【ConcurrentMapCacheManager】按照名字得到Cache【ConcurrentMapCache】组件
     *      2)、key使用keyGenerator生成的,默认是SimpleKeyGenerator
     *
     *
     *   几个属性:
     *      cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
     *
     *      key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值  1-方法的返回值
     *              编写SpEL; #i d;参数id的值   #a0  #p0  #root.args[0]
     *              getEmp[2]
     *
     *      keyGenerator:key的生成器;可以自己指定key的生成器的组件id
     *              key/keyGenerator:二选一使用;
     *
     *
     *      cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器
     *
     *      condition:指定符合条件的情况下才缓存;
     *              ,condition = "#id>0"
     *          condition = "#a0>1":第一个参数的值》1的时候才进行缓存
     *
     *      unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断
     *              unless = "#result == null"
     *              unless = "#a0==2":如果第一个参数的值是2,结果不缓存;
     *      sync:是否使用异步模式
     * @param id
     * @return
     *
     */
    @Cacheable(value = {"emp"}/*key="#id",keyGenerator = "myKeyGenerator",condition = "#a0>1",unless = "#a0==2"*/)
    public Employee getEmp(Integer id){
        System.out.println("查询"+id+"号员工");
        Employee emp = employeeMapper.getEmpById(id);
        return emp;
    }

    /**
     * @CachePut:既调用方法,又更新缓存数据;同步更新缓存
     * 修改了数据库的某个数据,同时更新缓存;
     * 运行时机:
     *  1、先调用目标方法
     *  2、将目标方法的结果缓存起来
     *
     * 测试步骤:
     *  1、查询1号员工;查到的结果会放在缓存中;
     *          key:1  value:lastName:张三
     *  2、以后查询还是之前的结果
     *  3、更新1号员工;【lastName:zhangsan;gender:0】
     *          将方法的返回值也放进缓存了;
     *          key:传入的employee对象  值:返回的employee对象;
     *  4、查询1号员工?
     *      应该是更新后的员工;
     *          key = "#employee.id":使用传入的参数的员工id;
     *          key = "#result.id":使用返回后的id
     *             @Cacheable的key是不能用#result
     *      为什么是没更新前的?【1号员工没有在缓存中更新】
     *
     */
    @CachePut(/*value = "emp",*/key = "#result.id")
    public Employee updateEmp(Employee employee){
        System.out.println("updateEmp:"+employee);
        employeeMapper.updateEmp(employee);
        return employee;
    }

    /**
     * @CacheEvict:缓存清除
     *  key:指定要清除的数据
     *  allEntries = true:指定清除这个缓存中所有的数据
     *  beforeInvocation = false:缓存的清除是否在方法之前执行
     *      默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除
     *
     *  beforeInvocation = true:
     *      代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除
     *
     *
     */
    @CacheEvict(value="emp",beforeInvocation = true/*key = "#id",*/)
    public void deleteEmp(Integer id){
        System.out.println("deleteEmp:"+id);
        //employeeMapper.deleteEmpById(id);
        int i = 10/0;
    }

    // @Caching 定义复杂的缓存规则
    @Caching(
            cacheable = {
                    @Cacheable(/*value="emp",*/key = "#lastName")
            },
            put = {
                    @CachePut(/*value="emp",*/key = "#result.id"),
                    @CachePut(/*value="emp",*/key = "#result.email")
            }
    )
    public Employee getEmpByLastName(String lastName){
        return employeeMapper.getEmpByLastName(lastName);
    }

}
  • spring整合redis的cache
  1. maven仓库添加依赖
    <dependency>
         <groupId>org.springframework.data</groupId>
         <artifactId>spring-data-redis</artifactId>
    </dependency>

     

  2. application.propertity配置redis端
    spring.redis.host=172.20.180.193

     

  3. springboot 1.5自己定制缓存规则
    @Configuration
    public class MyRedisConfig {
    
        @Bean
        public RedisTemplate<Object, Employee> empRedisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                throws UnknownHostException {
            RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
            template.setConnectionFactory(redisConnectionFactory);
            Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
            template.setDefaultSerializer(ser);
            return template;
        }
        @Bean
        public RedisTemplate<Object, Department> deptRedisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                throws UnknownHostException {
            RedisTemplate<Object, Department> template = new RedisTemplate<Object, Department>();
            template.setConnectionFactory(redisConnectionFactory);
            Jackson2JsonRedisSerializer<Department> ser = new Jackson2JsonRedisSerializer<Department>(Department.class);
            template.setDefaultSerializer(ser);
            return template;
        }
    
    
    
        //CacheManagerCustomizers可以来定制缓存的一些规则
        @Primary  //将某个缓存管理器作为默认的
        @Bean
        public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
            RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
            //key多了一个前缀
    
            //使用前缀,默认会将CacheName作为key的前缀
            cacheManager.setUsePrefix(true);
    
            return cacheManager;
        }
    
        @Bean
        public RedisCacheManager deptCacheManager(RedisTemplate<Object, Department> deptRedisTemplate){
            RedisCacheManager cacheManager = new RedisCacheManager(deptRedisTemplate);
            //key多了一个前缀
    
            //使用前缀,默认会将CacheName作为key的前缀
            cacheManager.setUsePrefix(true);
    
            return cacheManager;
        }
    
    
    }

    4.使用自己设置的存储规则,不使用序列化

    @Configuration
    public class MyRedisConfig {
    
        @Bean
        public RedisTemplate<Object, Employee> empRedisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                throws UnknownHostException {
            RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
            template.setConnectionFactory(redisConnectionFactory);
            Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
            template.setDefaultSerializer(ser);
            return template;
        }
        @Bean
        public RedisTemplate<Object, Department> deptRedisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                throws UnknownHostException {
            RedisTemplate<Object, Department> template = new RedisTemplate<Object, Department>();
            template.setConnectionFactory(redisConnectionFactory);
            Jackson2JsonRedisSerializer<Department> ser = new Jackson2JsonRedisSerializer<Department>(Department.class);
            template.setDefaultSerializer(ser);
            return template;
        }
    
    
    
        //CacheManagerCustomizers可以来定制缓存的一些规则
        @Primary  //将某个缓存管理器作为默认的
        @Bean
        public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
            RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
            //key多了一个前缀
    
            //使用前缀,默认会将CacheName作为key的前缀
            cacheManager.setUsePrefix(true);
    
            return cacheManager;
        }
    
        @Bean
        public RedisCacheManager deptCacheManager(RedisTemplate<Object, Department> deptRedisTemplate){
            RedisCacheManager cacheManager = new RedisCacheManager(deptRedisTemplate);
            //key多了一个前缀
    
            //使用前缀,默认会将CacheName作为key的前缀
            cacheManager.setUsePrefix(true);
    
            return cacheManager;
        }
    }

     

 

 

 

 

 

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot 的相关文章

随机推荐

  • Java自定义输出JSON格式

    如何自定义输出数据Json格式解决办法 平时默认的json输出格式为 xff1a span class token punctuation span span class token string 34 id 34 span span cl
  • SpringCloud常见问题 -- 启动多个服务

  • Spring框架 -- 项目启动及配置(一)

    Spring 容器启动大致流程 Spring 基础 IDEA项目Maven搭建结构 idea src src main java 自建 src main resource 自建 src main resource dev 自建 src ma
  • 【ZYNQ】裸机 PS + PL 双网口实现之 lwip 库文件修改

    因项目需要 xff0c 为实现 Zynq 裸机双网口通信功能 xff0c 其中 ENET0 连接 PS 端网口 xff0c ENET1 通过 EMIO 扩展连接 PL 端网口 xff0c 原 Lwip 库无板载 PHY 芯片支持及 EMIO
  • openstack删除nova service-list中的computer服务列表流程

    文章目录 说明 删除流程 nova服务查看 修改主机名 关闭准备删除的nova服务 删除nova服务 删除agent服务 创建虚拟机测试 说明 如下图 同一个计算节点主机名有2个 造成这种原因就是单纯的改主机名了 因为正常来说计算节点nov
  • spring— Bean标签scope配置和生命周期配置

    scope配置 singleton 默认值 xff0c 单例的prototype 多例的request WEB 项目中 xff0c Spring 创建一个 Bean的对象 xff0c 将对象存入到 request 域中session WEB
  • 对项目的梳理、流程和总结

    过程 我在制作 中国汽车技术研究中心 的一个演讲PPT前 xff0c 也已经有第一版的基础了 xff0c 不过 xff0c 第一版的PPT客户并不满意 xff0c 因为这个风格不是客户想要的 xff0c 所以客户对第一版的PPT并不是很满意
  • Linux中添加用户设置权限并实现远程登录

    1 username 为你自己命名的用户名 useradd username 2 设置密码 passwd username 3 用户文件夹在 home 下 4 查看更改登录管理账号 sudo vi etc ssh sshd config 5
  • rosdep init报错解决方法

    rosdep init报错解决方法 很多小伙伴在安装ROS的过程中都不可避免的要执行rosdep init和rosdep update这两行命令行 xff0c 这也是在安装ROS的过程中最让人头疼的两步 xff0c 一般都没法一次成功 xf
  • win10登录出现“其他用户”,一分钟后自动重启的解决方案和原因分析

    今天公司的同事的电脑莫名其妙重启开机后 xff0c 就一直是其他用户 身为技术部的人 xff0c 程序员就该修电脑是常识 xff08 大雾 xff09 百度各种解决方案的汇总 输入你的微软账号用户名 xff08 邮箱 xff09 和微软账号
  • Nginx启动失败control process exited, code=exited status=1

    出现现象 nginx启动失败 xff0c 估计是端口被某个进程占用了 通过lsof i 80 查看 xff0c 发现被httpd服务占用 可以通过杀掉进程或者更改nginx 端口解决 xff0c 通cat etc nginx nginx c
  • Python爬虫入门实例一之淘宝商品页面的爬取

    文章目录 1 爬取原界面2 代码解析3 完整代码引用源自 1 爬取原界面 今天给大家介绍第一个爬虫小例子 xff0c 使用requests库爬取淘宝商品信息 xff0c 首先想要爬取的内容如下图 2 代码解析 使用交互环境给大家带来代码解析
  • Linux(Ubuntu)入门——1.Ubuntu虚拟机安装

    inux Ubuntu 入门 1 Ubuntu虚拟机安装 目录 Ubuntu虚拟机安装 Ubuntu虚拟机安装 1 在VMware界面选择创建新的虚拟机 2 选择自定义 xff08 高级 xff09 xff0c 然后点击下一步 3 硬件兼容
  • Linux(Ubuntu)入门——4.VMwaretools安装(解决虚拟机窗口过小)

    Linux Ubuntu 入门 4 VMwaretools安装 xff08 解决虚拟机窗口过小 xff09 1 虚拟机选项卡里选择安装VMwareTools 2 桌面会看到VMware Tools的图标 xff0c 双击打开 3 将以 ta
  • Java0608-node

    Java0608 node 目录 Java0608 node1 数组1 1概念1 2 数组的使用1 3使用场景1 4应用 2 二维数组2 1二维数组的创建 1 数组 1 1概念 数组是指内存中一块连续的空间 xff0c 数量固定且存储类型相
  • Linux修改密码报错Authentication token manipulation error的终极解决方法

    文章目录 报错说明解决思路流程排查特殊权限有没有上锁查看根目录和关闭selinux etc pam d passwd文件 etc pam d system auth文件终极办法 xff0c 手动定义密码passwd Have exhaust
  • java0614-homework

    java0614 homework 目录 java0614 homework1 定义狗类2 求矩形面积3 实现级联菜单4 模拟计算器5 用户登录 1 定义狗类 题目 定义狗类 属性 xff1a 昵称 xff0c 品种 xff0c 健康值 x
  • Java0621-node

    Java0621 node 目录 1 JDK常用的类1 1 学习标准1 2 学习方法1 3 String1 3 1 定义1 3 2 构造方法1 3 3 方法1 3 3 1 字符串属性相关1 3 3 2 字符串比较1 3 3 3 索引1 3
  • 关于我使用的安卓View Binding方式

    方案有 xff1a ButterKnife findViewById View Binding 下面看下View Binding在下面的场景怎么使用 Activities Fragments Inflate Bind RecyclerVie
  • SpringBoot

    resources application properties xff1a Spring Boot应用的配置文件 xff1b 可以修改一些默认设置 xff1b server port 61 8081 改变默认端口号 使用SpringMVC