Spring Boot与缓存

jsr-107

Java Caching定义了5个核心接口分别是CachingProvider, CacheManager, Cache, Entry 和 Expiry

CachingProvider定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可以在运行期访问多个CachingProvider。

CacheManager定义了创建、配置、获取、管理和控制多个唯一命名的Cache,这些Cache存在于CacheManager的上下文中。一个CacheManager仅被一个CachingProvider所拥有。

Cache是一个类似Map的数据结构并临时存储以Key为索引的值。一个Cache仅被一个CacheManager所拥有。

Entry是一个存储在Cache中的key-value对。

Expiry 每一个存储在Cache中的条目有一个定义的有效期。一旦超过这个时间,条目为过期的状态。一旦过期,条目将不可访问、更新和删除。缓存有效期可以通过ExpiryPolicy设置。

Spring缓存抽象

Spring从3.1开始定义了org.springframework.cache.Cache
和org.springframework.cache.CacheManager接口来统一不同的缓存技术;
并支持使用JCache(JSR-107)注解简化我们开发;

Cache接口为缓存的组件规范定义,包含缓存的各种操作集合;
Cache接口下Spring提供了各种xxxCache的实现;如RedisCache,EhCacheCache , ConcurrentMapCache等;

每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取。
使用Spring缓存抽象时我们需要关注以下两点;
1、确定方法需要被缓存以及他们的缓存策略
2、从缓存中读取之前缓存存储的数据

初试缓存Cache:

启动类:

  1. package com.mikey.cache;
  2.  
  3. import org.mybatis.spring.annotation.MapperScan;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.cache.annotation.EnableCaching;
  7.  
  8. @MapperScan(value = "com.mikey.cache.mapper")
  9. @SpringBootApplication
  10. @EnableCaching//开启缓存
  11. public class Springboot01CacheApplication {
  12.  
  13. public static void main(String[] args) {
  14. SpringApplication.run(Springboot01CacheApplication.class, args);
  15. }
  16. }

配置文件:

  1. spring.datasource.url=jdbc:mysql://localhost:3306/spring_cache
  2. spring.datasource.username=root
  3. spring.datasource.password=root
  4. #spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  5. mybatis.configuration.multiple-result-sets-enabled=true
  6. logging.level.com.mikey.cache.mapper=debug

application.properties

Mapper:

  1. package com.mikey.cache.mapper;
  2.  
  3. import com.mikey.cache.bean.Employee;
  4. import org.apache.ibatis.annotations.*;
  5. import org.springframework.stereotype.Component;
  6.  
  7. /**
  8. * @author Mikey
  9. * @Title:
  10. * @Description:
  11. * @date 2018/10/25 22:40
  12. * @Version 1.0
  13. */
  14. @Component
  15. @Mapper
  16. public interface EmployeeMapper {
  17. @Select("select * from employee where id=#{id}")
  18. public Employee getEmpById(Integer id);
  19.  
  20. @Update("update employee set lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{d_id} where id=#{id}")
  21. public void updateEmp(Employee employee);
  22.  
  23. @Delete("Delete from employee where id=#{id}")
  24. public void deleteEmpById(Integer id);
  25.  
  26. @Insert("insert employee(lastName,email,gender,d_id) values(#{lastName},#{email},#{gender},#{dId}")
  27. public void insertEmployee(Employee employee);
  28. }

EmployeeMapper

Service:

  1. package com.mikey.cache.service;
  2.  
  3. import com.mikey.cache.bean.Employee;
  4. import com.mikey.cache.mapper.EmployeeMapper;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.cache.annotation.Cacheable;
  7. import org.springframework.stereotype.Service;
  8.  
  9. /**
  10. * @author Mikey
  11. * @Title:
  12. * @Description:
  13. * @date 2018/10/25 22:58
  14. * @Version 1.0
  15. */
  16. @Service
  17. public class EmployeeService {
  18. @Autowired
  19. EmployeeMapper employeeMapper;
  20.  
  21. /**
  22. * 将方法的运行结果进行缓存
  23. * @param id
  24. * @return
  25. */
  26. // @Cacheable(cacheNames = "emp",key = "#id")
  27. @Cacheable(cacheNames = "emp",condition = "#id>0",unless = "#result==null")
  28. public Employee getEmp(Integer id){
  29. System.out.println("查询"+id+"号员工");
  30. Employee employee=employeeMapper.getEmpById(id);
  31. return employee;
  32. }
  33. }

EmployeeService

Controller:

  1. package com.mikey.cache.controller;
  2.  
  3. import com.mikey.cache.bean.Employee;
  4. import com.mikey.cache.service.EmployeeService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10.  
  11. /**
  12. * @author Mikey
  13. * @Title:
  14. * @Description:
  15. * @date 2018/10/25 23:00
  16. * @Version 1.0
  17. */
  18. @RestController
  19. public class EmployeeController {
  20.  
  21. @Autowired
  22. EmployeeService employeeService;
  23.  
  24. @RequestMapping("/emp/{id}")
  25. public Employee getEmployee(@PathVariable("id") Integer id){
  26. return employeeService.getEmp(id);
  27. }
  28.  
  29. }

EmployeeController

原理:

  1. 将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法;
  2. CacheManager管理多个Cache组件的,对缓存的真正CRUD操作在Cache组件中,每一个缓存组件有自己唯一一个名字;
  3.  
  4. 原理:
  5. 1、自动配置类;CacheAutoConfiguration
  6. 2、缓存的配置类
  7. org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
  8. org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
  9. org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
  10. org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
  11. org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
  12. org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
  13. org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
  14. org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
  15. org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
  16. org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration【默认】
  17. org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
  18. 3、哪个配置类默认生效:SimpleCacheConfiguration

运行流程:

  1. 4、给容器中注册了一个CacheManagerConcurrentMapCacheManager
  2. 5、可以获取和创建ConcurrentMapCache类型的缓存组件;他的作用将数据保存在ConcurrentMap中;
  3.  
  4. 运行流程:
  5. @Cacheable
  6. 1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
  7. CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
  8. 2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
  9. key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key
  10. SimpleKeyGenerator生成key的默认策略;
  11. 如果没有参数;key=new SimpleKey();
  12. 如果有一个参数:key=参数的值
  13. 如果有多个参数:key=new SimpleKey(params);
  14. 3、没有查到缓存就调用目标方法;
  15. 4、将目标方法返回的结果,放进缓存中
  16.  
  17. @Cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
  18. 如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
  19.  
  20. 核心:
  21. 1)、使用CacheManagerConcurrentMapCacheManager】按照名字得到CacheConcurrentMapCache】组件
  22. 2)、key使用keyGenerator生成的,默认是SimpleKeyGenerator
  23.  
  24. 几个属性:
  25. cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
  26.  
  27. key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值 1-方法的返回值
  28. 编写SpEL #i d;参数id的值 #a0 #p0 #root.args[0]
  29. getEmp[2]
  30.  
  31. keyGeneratorkey的生成器;可以自己指定key的生成器的组件id
  32. key/keyGenerator:二选一使用;
  33.  
  34. cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器
  35.  
  36. condition:指定符合条件的情况下才缓存;
  37. ,condition = "#id>0"
  38. condition = "#a0>1":第一个参数的值》1的时候才进行缓存
  39.  
  40. unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断
  41. unless = "#result == null"
  42. unless = "#a0==2":如果第一个参数的值是2,结果不缓存;
  43. sync:是否使用异步模式

自定义Key生成器:

  1. package com.mikey.cache.config;
  2.  
  3. import org.springframework.cache.interceptor.KeyGenerator;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6.  
  7. import java.lang.reflect.Method;
  8. import java.util.Arrays;
  9.  
  10. /**
  11. * @author Mikey
  12. * @Title:
  13. * @Description:
  14. * @date 2018/10/26 15:21
  15. * @Version 1.0
  16. */
  17. @Configuration
  18. public class MyCacheConfig {
  19. @Bean("myKeyGenerator")
  20. public KeyGenerator keyGenerator(){
  21. return new KeyGenerator(){
  22. @Override
  23. public Object generate(Object target, Method method, Object... params) {
  24. return method.getName()+"["+ Arrays.asList(params).toString()+"]";
  25. }
  26. };
  27. }
  28. }

MyCacheConfig

注意:使用异步不支持unless

@CachePut:

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

缓存的同key不同Value/cacheName;

参考:http://www.bubuko.com/infodetail-2378163.html

@CacheEvict:缓存清除:

key:指定要清除的数据
 allEntries = true:指定清除这个缓存中所有的数据
 beforeInvocation = false:缓存的清除是否在方法之前执行
     默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除

 beforeInvocation = true:
     代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除

  1. @CacheEvict(value="emp",beforeInvocation = true/*key = "#id",*/)
  2. public void deleteEmp(Integer id){
  3. System.out.println("deleteEmp:"+id);
  4. //employeeMapper.deleteEmpById(id);
  5. int i = 10/0;
  6. }

@Caching 定义复杂的缓存规则

  1. // @Caching 定义复杂的缓存规则
  2. @Caching(
  3. cacheable = {
  4. @Cacheable(/*value="emp",*/key = "#lastName")
  5. },
  6. put = {
  7. @CachePut(/*value="emp",*/key = "#result.id"),
  8. @CachePut(/*value="emp",*/key = "#result.email")
  9. }
  10. )
  11. public Employee getEmpByLastName(String lastName){
  12. return employeeMapper.getEmpByLastName(lastName);
  13. }

@CacheConfig:

  1. /*
  2. * Copyright 2002-2015 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package org.springframework.cache.annotation;
  18.  
  19. import java.lang.annotation.Documented;
  20. import java.lang.annotation.ElementType;
  21. import java.lang.annotation.Retention;
  22. import java.lang.annotation.RetentionPolicy;
  23. import java.lang.annotation.Target;
  24.  
  25. /**
  26. * {@code @CacheConfig} provides a mechanism for sharing common cache-related
  27. * settings at the class level.
  28. *
  29. * <p>When this annotation is present on a given class, it provides a set
  30. * of default settings for any cache operation defined in that class.
  31. *
  32. * @author Stephane Nicoll
  33. * @author Sam Brannen
  34. * @since 4.1
  35. */
  36. @Target(ElementType.TYPE)
  37. @Retention(RetentionPolicy.RUNTIME)
  38. @Documented
  39. public @interface CacheConfig {
  40.  
  41. /**
  42. * Names of the default caches to consider for caching operations defined
  43. * in the annotated class.
  44. * <p>If none is set at the operation level, these are used instead of the default.
  45. * <p>May be used to determine the target cache (or caches), matching the
  46. * qualifier value or the bean names of a specific bean definition.
  47. */
  48. String[] cacheNames() default {};
  49.  
  50. /**
  51. * The bean name of the default {@link org.springframework.cache.interceptor.KeyGenerator} to
  52. * use for the class.
  53. * <p>If none is set at the operation level, this one is used instead of the default.
  54. * <p>The key generator is mutually exclusive with the use of a custom key. When such key is
  55. * defined for the operation, the value of this key generator is ignored.
  56. */
  57. String keyGenerator() default "";
  58.  
  59. /**
  60. * The bean name of the custom {@link org.springframework.cache.CacheManager} to use to
  61. * create a default {@link org.springframework.cache.interceptor.CacheResolver} if none
  62. * is set already.
  63. * <p>If no resolver and no cache manager are set at the operation level, and no cache
  64. * resolver is set via {@link #cacheResolver}, this one is used instead of the default.
  65. * @see org.springframework.cache.interceptor.SimpleCacheResolver
  66. */
  67. String cacheManager() default "";
  68.  
  69. /**
  70. * The bean name of the custom {@link org.springframework.cache.interceptor.CacheResolver} to use.
  71. * <p>If no resolver and no cache manager are set at the operation level, this one is used
  72. * instead of the default.
  73. */
  74. String cacheResolver() default "";
  75.  
  76. }

CacheConfig

完整文件:

  1. package com.atguigu.cache.service;
  2.  
  3. import com.atguigu.cache.bean.Employee;
  4. import com.atguigu.cache.mapper.EmployeeMapper;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.cache.annotation.*;
  7. import org.springframework.stereotype.Service;
  8.  
  9. @CacheConfig(cacheNames="emp"/*,cacheManager = "employeeCacheManager"*/) //抽取缓存的公共配置
  10. @Service
  11. public class EmployeeService {
  12.  
  13. @Autowired
  14. EmployeeMapper employeeMapper;
  15.  
  16. /**
  17. * 将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法;
  18. * CacheManager管理多个Cache组件的,对缓存的真正CRUD操作在Cache组件中,每一个缓存组件有自己唯一一个名字;
  19. *
  20.  
  21. *
  22. * 原理:
  23. * 1、自动配置类;CacheAutoConfiguration
  24. * 2、缓存的配置类
  25. * org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
  26. * org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
  27. * org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
  28. * org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
  29. * org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
  30. * org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
  31. * org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
  32. * org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
  33. * org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
  34. * org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration【默认】
  35. * org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
  36. * 3、哪个配置类默认生效:SimpleCacheConfiguration;
  37. *
  38. * 4、给容器中注册了一个CacheManager:ConcurrentMapCacheManager
  39. * 5、可以获取和创建ConcurrentMapCache类型的缓存组件;他的作用将数据保存在ConcurrentMap中;
  40. *
  41. * 运行流程:
  42. * @Cacheable:
  43. * 1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
  44. * (CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
  45. * 2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
  46. * key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key;
  47. * SimpleKeyGenerator生成key的默认策略;
  48. * 如果没有参数;key=new SimpleKey();
  49. * 如果有一个参数:key=参数的值
  50. * 如果有多个参数:key=new SimpleKey(params);
  51. * 3、没有查到缓存就调用目标方法;
  52. * 4、将目标方法返回的结果,放进缓存中
  53. *
  54. * @Cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
  55. * 如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
  56. *
  57. * 核心:
  58. * 1)、使用CacheManager【ConcurrentMapCacheManager】按照名字得到Cache【ConcurrentMapCache】组件
  59. * 2)、key使用keyGenerator生成的,默认是SimpleKeyGenerator
  60. *
  61. *
  62. * 几个属性:
  63. * cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
  64. *
  65. * key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值 1-方法的返回值
  66. * 编写SpEL; #i d;参数id的值 #a0 #p0 #root.args[0]
  67. * getEmp[2]
  68. *
  69. * keyGenerator:key的生成器;可以自己指定key的生成器的组件id
  70. * key/keyGenerator:二选一使用;
  71. *
  72. *
  73. * cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器
  74. *
  75. * condition:指定符合条件的情况下才缓存;
  76. * ,condition = "#id>0"
  77. * condition = "#a0>1":第一个参数的值》1的时候才进行缓存
  78. *
  79. * unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断
  80. * unless = "#result == null"
  81. * unless = "#a0==2":如果第一个参数的值是2,结果不缓存;
  82. * sync:是否使用异步模式
  83. * @param id
  84. * @return
  85. *
  86. */
  87. @Cacheable(value = {"emp"}/*,keyGenerator = "myKeyGenerator",condition = "#a0>1",unless = "#a0==2"*/)
  88. public Employee getEmp(Integer id){
  89. System.out.println("查询"+id+"号员工");
  90. Employee emp = employeeMapper.getEmpById(id);
  91. return emp;
  92. }
  93.  
  94. /**
  95. * @CachePut:既调用方法,又更新缓存数据;同步更新缓存
  96. * 修改了数据库的某个数据,同时更新缓存;
  97. * 运行时机:
  98. * 1、先调用目标方法
  99. * 2、将目标方法的结果缓存起来
  100. *
  101. * 测试步骤:
  102. * 1、查询1号员工;查到的结果会放在缓存中;
  103. * key:1 value:lastName:张三
  104. * 2、以后查询还是之前的结果
  105. * 3、更新1号员工;【lastName:zhangsan;gender:0】
  106. * 将方法的返回值也放进缓存了;
  107. * key:传入的employee对象 值:返回的employee对象;
  108. * 4、查询1号员工?
  109. * 应该是更新后的员工;
  110. * key = "#employee.id":使用传入的参数的员工id;
  111. * key = "#result.id":使用返回后的id
  112. * @Cacheable的key是不能用#result
  113. * 为什么是没更新前的?【1号员工没有在缓存中更新】
  114. *
  115. */
  116. @CachePut(/*value = "emp",*/key = "#result.id")
  117. public Employee updateEmp(Employee employee){
  118. System.out.println("updateEmp:"+employee);
  119. employeeMapper.updateEmp(employee);
  120. return employee;
  121. }
  122.  
  123. /**
  124. * @CacheEvict:缓存清除
  125. * key:指定要清除的数据
  126. * allEntries = true:指定清除这个缓存中所有的数据
  127. * beforeInvocation = false:缓存的清除是否在方法之前执行
  128. * 默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除
  129. *
  130. * beforeInvocation = true:
  131. * 代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除
  132. *
  133. *
  134. */
  135. @CacheEvict(value="emp",beforeInvocation = true/*key = "#id",*/)
  136. public void deleteEmp(Integer id){
  137. System.out.println("deleteEmp:"+id);
  138. //employeeMapper.deleteEmpById(id);
  139. int i = 10/0;
  140. }
  141.  
  142. // @Caching 定义复杂的缓存规则
  143. @Caching(
  144. cacheable = {
  145. @Cacheable(/*value="emp",*/key = "#lastName")
  146. },
  147. put = {
  148. @CachePut(/*value="emp",*/key = "#result.id"),
  149. @CachePut(/*value="emp",*/key = "#result.email")
  150. }
  151. )
  152. public Employee getEmpByLastName(String lastName){
  153. return employeeMapper.getEmpByLastName(lastName);
  154. }
  155.  
  156. }

EmployeeService.java

整合Redis

引入spring-boot-starter-data-redis
application.yml配置redis连接地址
使用RestTemplate操作redis
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
配置缓存、CacheManagerCustomizers
测试使用缓存、切换缓存、 CompositeCacheManager

安装镜像:

连接:

引入redis启动器:

官网:

配置redis:

  1. package com.mikey.cache;
  2.  
  3. import com.mikey.cache.bean.Employee;
  4. import com.mikey.cache.mapper.EmployeeMapper;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.data.redis.core.RedisTemplate;
  10. import org.springframework.data.redis.core.StringRedisTemplate;
  11. import org.springframework.test.context.junit4.SpringRunner;
  12.  
  13. @RunWith(SpringRunner.class)
  14. @SpringBootTest
  15. public class Springboot01CacheApplicationTests {
  16.  
  17. @Autowired
  18. EmployeeMapper employeeMapper;
  19. @Autowired
  20. StringRedisTemplate stringRedisTemplate;//操作字符串
  21. @Autowired
  22. RedisTemplate redisTemplate;//k-v都是对象
  23.  
  24. @Test
  25. public void contextLoads() {
  26. Employee employee=employeeMapper.getEmpById(1);
  27. System.out.println("Message="+employee);
  28. }
  29.  
  30. @Test
  31. public void testRedis(){
  32. // stringRedisTemplate.opsForValue().append("msg","hello");
  33. // String msg = stringRedisTemplate.opsForValue().get("msg");
  34. // System.out.println("Message="+msg);
  35. stringRedisTemplate.opsForList().leftPush("mylist","1");
  36. stringRedisTemplate.opsForList().leftPush("mylist","2");
  37. }
  38.  
  39. @Test
  40. public void testObjectRedis(){
  41. Employee employee=employeeMapper.getEmpById(1);
  42. redisTemplate.opsForValue().set("emp-01",employee);
  43. }
  44.  
  45. }

测试类

将数据以json储存:

  方法1:将数据直接转成json

  方法2:配置:

配置类:

  1. package com.mikey.cache.config;
  2.  
  3. import com.mikey.cache.bean.Employee;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.data.redis.connection.RedisConnectionFactory;
  7. import org.springframework.data.redis.core.RedisTemplate;
  8. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  9.  
  10. /**
  11. * @author Mikey
  12. * @Title:
  13. * @Description:
  14. * @date 2018/10/26 19:45
  15. * @Version 1.0
  16. */
  17. @Configuration
  18. public class MyRedisConfig {
  19. @Bean
  20. public RedisTemplate<Object, Employee> empredisTemplate(
  21. RedisConnectionFactory redisConnectionFactory) throws Exception{
  22. RedisTemplate<Object,Employee> template=new RedisTemplate<Object, Employee>();
  23. template.setConnectionFactory(redisConnectionFactory);
  24. Jackson2JsonRedisSerializer<Employee> ser=new Jackson2JsonRedisSerializer<Employee>(Employee.class);
  25. template.setDefaultSerializer(ser);
  26. return template;
  27. }
  28. }

MyRedisConfig.java

测试类:

结果:

配置redis的json格式:

  1. package com.mikey.cache.config;
  2.  
  3. import com.mikey.cache.bean.Employee;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.data.redis.cache.RedisCacheManager;
  7. import org.springframework.data.redis.connection.RedisConnectionFactory;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  10.  
  11. /**
  12. * @author Mikey
  13. * @Title:
  14. * @Description:
  15. * @date 2018/10/26 19:45
  16. * @Version 1.0
  17. */
  18. @Configuration
  19. public class MyRedisConfig {
  20. @Bean
  21. public RedisTemplate<Object, Employee> empredisTemplate(
  22. RedisConnectionFactory redisConnectionFactory) throws Exception{
  23. RedisTemplate<Object,Employee> template=new RedisTemplate<Object, Employee>();
  24. template.setConnectionFactory(redisConnectionFactory);
  25. Jackson2JsonRedisSerializer<Employee> ser=new Jackson2JsonRedisSerializer<Employee>(Employee.class);
  26. template.setDefaultSerializer(ser);
  27. return template;
  28. }
  29. @Bean
  30. public RedisCacheManager empoyeeCacheManager(RedisTemplate<Object,Employee> employeeRedisTemplate){
  31. RedisCacheManager redisCacheManager=new RedisCacheManager(employeeRedisTemplate);
  32. redisCacheManager.setUsePrefix(true);
  33. return redisCacheManager;
  34. }
  35. }

MyRedisConfig

序列号及反序列化:

  1. package com.mikey.cache.config;
  2.  
  3. import com.mikey.cache.bean.Department;
  4. import com.mikey.cache.bean.Employee;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.context.annotation.Primary;
  8. import org.springframework.data.redis.cache.RedisCacheManager;
  9. import org.springframework.data.redis.connection.RedisConnectionFactory;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  12.  
  13. /**
  14. * @author Mikey
  15. * @Title:
  16. * @Description:
  17. * @date 2018/10/26 19:45
  18. * @Version 1.0
  19. */
  20. @Configuration
  21. public class MyRedisConfig {
  22. @Bean
  23. public RedisTemplate<Object, Employee> empredisTemplate(
  24. RedisConnectionFactory redisConnectionFactory) throws Exception{
  25. RedisTemplate<Object,Employee> template=new RedisTemplate<Object, Employee>();
  26. template.setConnectionFactory(redisConnectionFactory);
  27. Jackson2JsonRedisSerializer<Employee> ser=new Jackson2JsonRedisSerializer<Employee>(Employee.class);
  28. template.setDefaultSerializer(ser);
  29. return template;
  30. }
  31. @Bean
  32. public RedisTemplate<Object, Department> deptredisTemplate(
  33. RedisConnectionFactory redisConnectionFactory) throws Exception{
  34. RedisTemplate<Object,Department> template=new RedisTemplate<Object, Department>();
  35. template.setConnectionFactory(redisConnectionFactory);
  36. Jackson2JsonRedisSerializer<Department> ser=new Jackson2JsonRedisSerializer<Department>(Department.class);
  37. template.setDefaultSerializer(ser);
  38. return template;
  39. }
  40. @Primary//必须设置一个默认的
  41. @Bean
  42. public RedisCacheManager empoyeeCacheManager(RedisTemplate<Object,Employee> employeeRedisTemplate){
  43. RedisCacheManager redisCacheManager=new RedisCacheManager(employeeRedisTemplate);
  44. redisCacheManager.setUsePrefix(true);
  45. return redisCacheManager;
  46. }
  47. @Bean
  48. public RedisCacheManager deptCacheManager(RedisTemplate<Object,Department> deptloyeeRedisTemplate){
  49. RedisCacheManager redisCacheManager=new RedisCacheManager(deptloyeeRedisTemplate);
  50. redisCacheManager.setUsePrefix(true);
  51. return redisCacheManager;
  52. }
  53. }

MyRedisConfig

直接使用缓存管理器

  1. /**
  2. * @author Mikey
  3. * @Title:
  4. * @Description:
  5. * @date 2018/10/26 20:53
  6. * @Version 1.0
  7. */
  8. @RestController
  9. public class DeptController {
  10.  
  11. @Autowired
  12. @Qualifier("deptCacheManager")
  13. private RedisCacheManager deptCacheManager;
  14.  
  15. @Autowired
  16. private DeptService deptService;
  17.  
  18. @GetMapping("/dept/{id}")
  19. public Department getDeptById(@PathVariable("id") Integer id){
  20. return deptService.getDeptById(id);
  21. }
  22.  
  23. @GetMapping("/depts/{id}")
  24. public Department getDeptByIds(@PathVariable("id") Integer id){
  25. System.out.println("查询部门");
  26. Department department=deptService.getDeptById(1);
  27. Cache dept = deptCacheManager.getCache("dept");
  28. dept.put("dept:1",department);
  29. return department;
  30. }
  31.  
  32. }

Spring Boot与消息

1JMS:java消息服务

大多应用中,可通过消息服务中间件来提升系统异步通信、扩展解耦能力
消息服务中两个重要概念:
       消息代理(message broker)和目的地(destination)
当消息发送者发送消息以后,将由消息代理接管,消息代理保证消息传递到指定目的地。
消息队列主要有两种形式的目的地
队列(queue):点对点消息通信(point-to-point)
主题(topic):发布(publish)/订阅(subscribe)消息通信

点对点式:

消息发送者发送消息,消息代理将其放入一个队列中,消息接收者从队列中获取消息内容,消息读取后被移出队列
消息只有唯一的发送者和接受者,但并不是说只能有一个接收者

发布订阅式:

发送者(发布者)发送消息到主题,多个接收者(订阅者)监听(订阅)这个主题,那么就会在消息到达时同时收到消息

JMS(Java Message Service)JAVA消息服务:

基于JVM消息代理的规范。ActiveMQ、HornetMQ是JMS实现

2AMQP:高级查询队列协议

AMQP(Advanced Message Queuing Protocol)

高级消息队列协议,也是一个消息代理的规范,兼容JMS
RabbitMQ是AMQP的实现

Spring支持

spring-jms提供了对JMS的支持
spring-rabbit提供了对AMQP的支持
需要ConnectionFactory的实现来连接消息代理
提供JmsTemplate、RabbitTemplate来发送消息
@JmsListener(JMS)、@RabbitListener(AMQP)注解在方法上监听消息代理发布的消息
@EnableJms、@EnableRabbit开启支持

Spring Boot自动配置

JmsAutoConfiguration
RabbitAutoConfiguration

3RabbitMQ:

 RabbitMQ简介:
RabbitMQ是一个由erlang开发的AMQP(Advanved Message Queue Protocol)的开源实现。

核心概念
Message
消息,消息是不具名的,它由消息头和消息体组成。消息体是不透明的,而消息头则由一系列的可选属性组成,这些属性包括routing-key(路由键)、

priority(相对于其他消息的优先权)、delivery-mode(指出该消息可能需要持久性存储)等。

Publisher
消息的生产者,也是一个向交换器发布消息的客户端应用程序。

Exchange
交换器,用来接收生产者发送的消息并将这些消息路由给服务器中的队列。
Exchange有4种类型:direct(默认),fanout, topic, 和headers,不同类型的Exchange转发消息的策略有所区别

 Queue
消息队列,用来保存消息直到发送给消费者。它是消息的容器,也是消息的终点。一个消息可投入一个或多个队列。

消息一直在队列里面,等待消费者连接到这个队列将其取走。

Binding
绑定,用于消息队列和交换器之间的关联。一个绑定就是基于路由键将交换器和消息队列连接起来的路由规则,

所以可以将交换器理解成一个由绑定构成的路由表。
Exchange 和Queue的绑定可以是多对多的关系。

Connection
网络连接,比如一个TCP连接。

Channel
信道,多路复用连接中的一条独立的双向数据流通道。信道是建立在真实的TCP连接内的虚拟连接,AMQP 命令都是通过信道发出去的,

不管是发布消息、订阅队列还是接收消息,这些动作都是通过信道完成。因为对于操作系统来说建立和销毁 TCP 都是非常昂贵的开销,

所以引入了信道的概念,以复用一条 TCP 连接。

 Consumer
消息的消费者,表示一个从消息队列中取得消息的客户端应用程序。

Virtual Host
虚拟主机,表示一批交换器、消息队列和相关对象。虚拟主机是共享相同的身份认证和加密环境的独立服务器域。
每个 vhost 本质上就是一个 mini 版的 RabbitMQ 服务器,拥有自己的队列、交换器、绑定和权限机制。
vhost 是 AMQP 概念的基础,必须在连接时指定,RabbitMQ 默认的 vhost 是 / 。

Broker
表示消息队列服务器实体

RabbitMQ运行机制:

AMQP 中的消息路由
AMQP 中消息的路由过程和 Java 开发者熟悉的 JMS 存在一些差别,AMQP 中增加了 Exchange 和 Binding 的角色。生产者把消息发布到 Exchange 上,

消息最终到达队列并被消费者接收,而 Binding 决定交换器的消息应该发送到那个队列。

Exchange 类型

Exchange分发消息时根据类型的不同分发策略有区别,目前共四种类型:
direct、fanout、topic、headers 。headers 匹配 AMQP 消息的 header 而不是路由键,
 headers 交换器和 direct 交换器完全一致,但性能差很多,目前几乎用不到了,所以直接看另外三种类型:

每个发到 fanout 类型交换器的消息都会分到所有绑定的队列上去。fanout 交换器不处理路由键,
只是简单的将队列绑定到交换器上,每个发送到交换器的消息都会被转发到与该交换器绑定的所有队列上。
很像子网广播,每台子网内的主机都获得了一份复制的消息。fanout 类型转发消息是最快的。

topic 交换器通过模式匹配分配消息的路由键属性,将路由键和某个模式进行匹配,
此时队列需要绑定到一个模式上。它将路由键和绑定键的字符串切分成单词,这些单词之间用点隔开。
它同样也会识别两个通配符:符号“#”和符号“*”。#匹配0个或多个单词,*匹配一个单词。

RabbitMQ整合

引入 spring-boot-starter-amqp
application.yml配置
测试RabbitMQ
AmqpAdmin:管理组件
RabbitTemplate:消息发送处理组件

 

 无法访问管理页面?

springboot 整合消息队列:

自动配置
 1、RabbitAutoConfiguration
 2、有自动配置了连接工厂ConnectionFactory;
 3、RabbitProperties 封装了 RabbitMQ的配置
 4、 RabbitTemplate :给RabbitMQ发送和接受消息;
 5、 AmqpAdmin : RabbitMQ系统管理功能组件;
     AmqpAdmin:创建和删除 Queue,Exchange,Binding
 6、@EnableRabbit +  @RabbitListener 监听消息队列的内容

1.利用idea的spring初始化器创建应用选中RabbitMq模块

2.配置文件:

  1. spring.rabbitmq.addresses=47.106.210.183
  2. spring.rabbitmq.username=guest
  3. spring.rabbitmq.password=guest
  4. #spring.rabbitmq.port=5672//默认5672
  5. #spring.rabbitmq.virtual-host=

3.测试:

  1. package com.mikey.springbootamqp;
  2.  
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9.  
  10. import java.util.Arrays;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13.  
  14. @RunWith(SpringRunner.class)
  15. @SpringBootTest
  16. public class SpringbootAmqpApplicationTests {
  17. @Autowired
  18. private RabbitTemplate rabbitTemplate;
  19.  
  20. @Test
  21. public void contextLoads() {
  22. // rabbitTemplate.send(exchange,routeKey,message);
  23. Map<String,Object> map=new HashMap<>();
  24. map.put("msg","这是第一个消息");
  25. map.put("data", Arrays.asList("helloworld",123,true));
  26.  
  27. rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",map);
  28.  
  29. }
  30.  
  31. @Test
  32. public void receive(){
  33. Object o = rabbitTemplate.receiveAndConvert("atguigu.news");
  34. System.out.println("数据类型="+o.getClass());
  35. System.out.println("数据="+o);
  36. }
  37. }

Test

自定义messageconveter(json格式)

  1. package com.mikey.springbootamqp.config;
  2.  
  3. import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
  4. import org.springframework.amqp.support.converter.MessageConverter;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7.  
  8. /**
  9. * @author Mikey
  10. * @Title:
  11. * @Description:
  12. * @date 2018/10/27 10:26
  13. * @Version 1.0
  14. */
  15. @Configuration
  16. public class MyAMQPConfig {
  17. @Bean
  18. public MessageConverter messageConverter(){
  19. return new Jackson2JsonMessageConverter();
  20. }
  21. }

MyAMQPConfig .java

结果:

测试:

  1. package com.mikey.springbootamqp;
  2.  
  3. import com.mikey.springbootamqp.bean.Book;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10.  
  11. import java.util.Arrays;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14.  
  15. @RunWith(SpringRunner.class)
  16. @SpringBootTest
  17. public class SpringbootAmqpApplicationTests {
  18. @Autowired
  19. private RabbitTemplate rabbitTemplate;
  20.  
  21. @Test
  22. public void contextLoads() {
  23. // rabbitTemplate.send(exchange,routeKey,message);
  24. Map<String,Object> map=new HashMap<>();
  25. map.put("msg","这是第一个消息");
  26. map.put("data", Arrays.asList("helloworld",123,true));
  27.  
  28. rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",map);
  29.  
  30. }
  31.  
  32. @Test
  33. public void receive(){
  34. Object o = rabbitTemplate.receiveAndConvert("atguigu.news");
  35. System.out.println("数据类型="+o.getClass());
  36. System.out.println("数据="+o);
  37. }
  38.  
  39. /**
  40. * 发送javaBean
  41. */
  42. @Test
  43. public void testBeanSend(){
  44. Book book = new Book("阿姆斯特朗", "回旋喷气式加速炮");
  45. System.out.println("Book="+book);
  46. rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",book);
  47. }
  48.  
  49. /**
  50. * 接收对象
  51. */
  52. @Test
  53. public void getBeanSend(){
  54. Book book = (Book) rabbitTemplate.receiveAndConvert("atguigu.news");
  55. System.out.println("messsage="+book);
  56. }
  57.  
  58. /**
  59. * 广播发送
  60. */
  61. @Test
  62. public void sendAll(){
  63. rabbitTemplate.convertAndSend("exchange.fanout","",new Book("麦奇","麦奇"));
  64. }
  65. }

Test

消息监听器:

启动类添加注解:

2.编写监听器:

创建消息队列和交换器

  1. package com.mikey.springbootamqp;
  2.  
  3. import com.mikey.springbootamqp.bean.Book;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.amqp.core.AmqpAdmin;
  7. import org.springframework.amqp.core.Binding;
  8. import org.springframework.amqp.core.DirectExchange;
  9. import org.springframework.amqp.core.Queue;
  10. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.boot.test.context.SpringBootTest;
  13. import org.springframework.test.context.junit4.SpringRunner;
  14.  
  15. import java.util.Arrays;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18.  
  19. @RunWith(SpringRunner.class)
  20. @SpringBootTest
  21. public class SpringbootAmqpApplicationTests {
  22. @Autowired
  23. private RabbitTemplate rabbitTemplate;
  24.  
  25. @Autowired
  26. private AmqpAdmin amqpAdmin;//操作
  27.  
  28. /**
  29. * 添加Exchange
  30. */
  31. @Test
  32. public void createExchange(){
  33. amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
  34. System.out.println("创建完成");
  35. }
  36.  
  37. /**
  38. * 添加队列
  39. */
  40. @Test
  41. public void createQueue(){
  42. amqpAdmin.declareQueue(new Queue("amqpadmin.queue"));
  43. System.out.println("创建队列成功");
  44. }
  45.  
  46. /**
  47. * 添加绑定
  48. */
  49. @Test
  50. public void createBinding(){
  51. amqpAdmin.declareBinding(new Binding("amqpadmin.queue",Binding.DestinationType.QUEUE,"amqpadmin.exchange","ampq.haha",null));
  52. }
  53. }

Spring Boot与检索

我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的首选。他可以快速的存储、搜索和分析海量数据。
Spring Boot通过整合Spring Data ElasticSearch为我们提供了非常便捷的检索功能支持;

Elasticsearch是一个分布式搜索服务,提供Restful API,底层基于Lucene,采用多shard(分片)的方式保证数据安全,
并且提供自动resharding的功能,github等大型的站点也是采用了ElasticSearch作为其搜索服务,

docker安装:elasticSearch

docker运行命令:

  1. docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name ES01 5acf0e8da90b
    限制堆空间内存,elasticSearch默认占用2G

启动成功:

学习文档https://www.elastic.co/guide/cn/elasticsearch/guide/current/query-dsl-intro.html

概念:

以 员工文档 的形式存储为例:
一个文档代表一个员工数据。存储数据到 ElasticSearch 的行为叫做 索引 ,
但在索引一个文档之前,需要确定将文档存储在哪里。
一个 ElasticSearch 集群可以 包含多个 索引 ,相应的每个索引可以包含多个 类型 。
这些不同的类型存储着多个 文档 ,每个文档又有 多个 属性 。
类似关系:
索引-数据库
类型-表
文档-表中的记录
属性-列

 三、整合ElasticSearch测试

引入spring-boot-starter-data-elasticsearch
安装Spring Data 对应版本的ElasticSearch
application.yml配置
Spring Boot自动配置的
    ElasticsearchRepository、ElasticsearchTemplate、Jest
测试ElasticSearch

  1. /**
  2. * SpringBoot默认支持两种技术来和ES交互;
  3. * 1、Jest(默认不生效)
  4. * 需要导入jest的工具包(io.searchbox.client.JestClient)
  5. * 2、SpringData ElasticSearch【ES版本有可能不合适】
  6. * 版本适配说明:https://github.com/spring-projects/spring-data-elasticsearch
  7. * 如果版本不适配:2.4.6
  8. * 1)、升级SpringBoot版本
  9. * 2)、安装对应版本的ES
  10. *
  11. * 1)、Client 节点信息clusterNodes;clusterName
  12. * 2)、ElasticsearchTemplate 操作es
  13. * 3)、编写一个 ElasticsearchRepository 的子接口来操作ES;
  14. * 两种用法:https://github.com/spring-projects/spring-data-elasticsearch
  15. * 1)、编写一个 ElasticsearchRepository
  16. */

第一种:

配置文件:

先使用jest:

测试类:

  1. package com.mikey.springbootelasticsearch;
  2.  
  3. import com.mikey.springbootelasticsearch.bean.Article;
  4. import io.searchbox.client.JestClient;
  5. import io.searchbox.core.Index;
  6. import io.searchbox.core.Search;
  7. import io.searchbox.core.SearchResult;
  8. import org.junit.Test;
  9. import org.junit.runner.RunWith;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.boot.test.context.SpringBootTest;
  12. import org.springframework.test.context.junit4.SpringRunner;
  13.  
  14. import java.io.IOException;
  15.  
  16. @RunWith(SpringRunner.class)
  17. @SpringBootTest
  18. public class SpringbootelasticsearchApplicationTests {
  19.  
  20. @Autowired
  21. JestClient jestClient;
  22. @Test
  23. public void contextLoads() throws IOException {
  24. Article article = new Article();
  25. article.setId(1);
  26. article.setTitle("ElasticSearch");
  27. article.setAuthor("阿姆斯特朗炮");
  28. article.setContent("Hello world");
  29. Index build = new Index.Builder(article).index("atguigu").type("news").build();//构建一个索引功能
  30. jestClient.execute(build);
  31. }
  32.  
  33. /**
  34. * 测试搜索
  35. */
  36. @Test
  37. public void search() throws IOException {
  38. String json="{\n"+
  39. " \"query\" :{\n"+
  40. " \"match\" :{\n"+
  41. " \"content\" : \"hello\"\n"+
  42. " }\n"+
  43. " }\n"+
  44. "}";
  45. Search build = new Search.Builder(json).addIndex("atguigu").addType("news").build();
  46. SearchResult execute = jestClient.execute(build);
  47. System.out.println("Message="+execute.getJsonString());
  48. }
  49.  
  50. }

参考文档:https://github.com/searchbox-io/Jest/tree/master/jest

第二种:使用spring-boot-starter-data-elasticsearch

引入:在pom文件中spring-boot-starter-data-elasticsearch

配置文件:

编写bean:

  1. package com.mikey.springbootelasticsearch.bean;
  2.  
  3. import org.springframework.data.elasticsearch.annotations.Document;
  4.  
  5. /**
  6. * @author Mikey
  7. * @Title:
  8. * @Description:
  9. * @date 2018/10/27 16:00
  10. * @Version 1.0
  11. */
  12. @Document(indexName = "atguigu",type = "book")
  13. public class Book {
  14. private Integer id;
  15. private String bookName;
  16. private String author;
  17.  
  18. public Integer getId() {
  19. return id;
  20. }
  21.  
  22. public void setId(Integer id) {
  23. this.id = id;
  24. }
  25.  
  26. public String getBookName() {
  27. return bookName;
  28. }
  29.  
  30. public void setBookName(String bookName) {
  31. this.bookName = bookName;
  32. }
  33.  
  34. public String getAuthor() {
  35. return author;
  36. }
  37.  
  38. public void setAuthor(String author) {
  39. this.author = author;
  40. }
  41.  
  42. @Override
  43. public String toString() {
  44. return "Book{" +
  45. "id=" + id +
  46. ", bookName='" + bookName + '\'' +
  47. ", author='" + author + '\'' +
  48. '}';
  49. }
  50. }

编写接口:

  1. package com.atguigu.elastic.repository;
  2.  
  3. import com.atguigu.elastic.bean.Book;
  4. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  5.  
  6. import java.util.List;
  7.  
  8. public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
  9.  
  10. //参照
  11. // https://docs.spring.io/spring-data/elasticsearch/docs/3.0.6.RELEASE/reference/html/
  12. public List<Book> findByBookNameLike(String bookName);
  13.  
  14. }

测试类:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class Springboot03ElasticApplicationTests {
  4.  
  5. @Autowired
  6. JestClient jestClient;
  7.  
  8. @Autowired
  9. BookRepository bookRepository;
  10.  
  11. @Test
  12. public void test02(){
  13. // Book book = new Book();
  14. // book.setId(1);
  15. // book.setBookName("西游记");
  16. // book.setAuthor("吴承恩");
  17. // bookRepository.index(book);
  18.  
  19. for (Book book : bookRepository.findByBookNameLike("游")) {
  20. System.out.println(book);
  21. }
  22. ;
  23.  
  24. }
  25.  
  26. }

注意:要选择对应的版本不然会报连接超时异常:

参考文档:https://docs.spring.io/spring-data/elasticsearch/docs/3.0.6.RELEASE/reference/html/

Spring Boot与任务

异步任务:

在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,
容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,
就已经内置了@Async来完美解决这个问题。

两个注解:
@EnableAysnc、@Aysnc

启动类添加:

方法上:

定时任务:

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。
Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor TaskScheduler 接口。
两个注解:@EnableScheduling、@Scheduled
cron表达式:

代码实现:

启动类加入@EnableScheduling注解

  1. import org.springframework.scheduling.annotation.Scheduled;
  2. import org.springframework.stereotype.Service;
  3.  
  4. @Service
  5. public class ScheduledService {
  6.  
  7. /**
  8. * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
  9. * 0 * * * * MON-FRI
  10. * 【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
  11. * 【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
  12. * 【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
  13. * 【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
  14. * 【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
  15. */
  16. // @Scheduled(cron = "0 * * * * MON-SAT")
  17. //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
  18. // @Scheduled(cron = "0-4 * * * * MON-SAT")
  19. @Scheduled(cron = "0/4 * * * * MON-SAT") //每4秒执行一次
  20. public void hello(){
  21. System.out.println("hello ... ");
  22. }
  23. }

ScheduledService

邮件任务:

邮件发送需要引入spring-boot-starter-mail
Spring Boot 自动配置MailSenderAutoConfiguration
定义MailProperties内容,配置在application.yml中
自动装配JavaMailSender
测试邮件发送

代码操作:

1.映入相关的启动器依赖:

  1. org.springframework.boot

配置文件 :

测试类:

  1. package com.mikey.boottesk;
  2.  
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.mail.SimpleMailMessage;
  8. import org.springframework.mail.javamail.JavaMailSender;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10.  
  11. @RunWith(SpringRunner.class)
  12. @SpringBootTest
  13. public class SpringbootTeskApplicationTests {
  14.  
  15. @Autowired
  16. JavaMailSender javaMailSender;
  17. @Test
  18. public void contextLoads() {
  19. SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
  20. simpleMailMessage.setSubject("今晚行动");
  21. simpleMailMessage.setText("hello world");
  22. simpleMailMessage.setTo("18276297824@163.com");
  23. simpleMailMessage.setFrom("1625017540@qq.com");
  24. javaMailSender.send(simpleMailMessage);
  25. }
  26.  
  27. }

SpringbootTeskApplicationTests

成功发送:

报错问题:

如果报不安全连接需要ssl则在配置文件中配置

带复杂内容的邮件:

  1. package com.atguigu.task;
  2.  
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.mail.SimpleMailMessage;
  8. import org.springframework.mail.javamail.JavaMailSenderImpl;
  9. import org.springframework.mail.javamail.MimeMessageHelper;
  10. import org.springframework.test.context.junit4.SpringRunner;
  11.  
  12. import javax.mail.internet.MimeMessage;
  13. import java.io.File;
  14.  
  15. @RunWith(SpringRunner.class)
  16. @SpringBootTest
  17. public class Springboot04TaskApplicationTests {
  18.  
  19. @Autowired
  20. JavaMailSenderImpl mailSender;
  21.  
  22. @Test
  23. public void contextLoads() {
  24. SimpleMailMessage message = new SimpleMailMessage();
  25. //邮件设置
  26. message.setSubject("通知-今晚开会");
  27. message.setText("今晚7:30开会");
  28.  
  29. message.setTo("17512080612@163.com");
  30. message.setFrom("534096094@qq.com");
  31.  
  32. mailSender.send(message);
  33. }
  34.  
  35. @Test
  36. public void test02() throws Exception{
  37. //1、创建一个复杂的消息邮件
  38. MimeMessage mimeMessage = mailSender.createMimeMessage();
  39. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  40.  
  41. //邮件设置
  42. helper.setSubject("通知-今晚开会");
  43. helper.setText("<b style='color:red'>今天 7:30 开会</b>",true);
  44.  
  45. helper.setTo("17512080612@163.com");
  46. helper.setFrom("534096094@qq.com");
  47.  
  48. //上传文件
  49. helper.addAttachment("1.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\1.jpg"));
  50. helper.addAttachment("2.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\2.jpg"));
  51.  
  52. mailSender.send(mimeMessage);
  53.  
  54. }
  55.  
  56. }

Spring Boot与安全

两大安全框架:shiro,SpringSecutity

安全

SpringSecutity:

Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型。他可以实现强大的web安全控制。对于安全控制,我们仅需引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理。几个类:
WebSecurityConfigurerAdapter:自定义Security策略
AuthenticationManagerBuilder:自定义认证策略
@EnableWebSecurity:开启WebSecurity模式

应用程序的两个主要区域是“认证”和“授权”(或者访问控制)。这两个主要区域是Spring Security 的两个目标。

“认证”(Authentication),是建立一个他声明的主体的过程(一个“主体”一般是指用户,设备或一些可以在你的应用程序中执行动作的其他系统)。

“授权”(Authorization)指确定一个主体是否允许在你的应用程序执行一个动作的过程。为了抵达需要授权的店,主体的身份已经有认证过程建立。

这个概念是通用的而不只在Spring Security中。

二、Web&安全
登陆/注销
HttpSecurity配置登陆、注销功能
Thymeleaf提供的SpringSecurity标签支持
需要引入thymeleaf-extras-springsecurity4
sec:authentication=“name”获得当前用户的用户名
sec:authorize=“hasRole(‘ADMIN’)”当前用户必须拥有ADMIN权限时才会显示标签内容
remember me
表单添加remember-me的checkbox
配置启用remember-me功能
CSRF(Cross-site request forgery)跨站请求伪造
HttpSecurity启用csrf功能,会为表单添加_csrf的值,提交携带来预防CSRF;

初始化向导创建项目

引入web,thymelef模块

导入依赖:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5.  
  6. <groupId>com.mikey</groupId>
  7. <artifactId>springboot-security</artifactId>
  8. <version>0.0.1-SNAPSHOT</version>
  9. <packaging>jar</packaging>
  10.  
  11. <name>springboot-security</name>
  12. <description>Demo project for Spring Boot</description>
  13.  
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>1.5.17.RELEASE</version>
  18. <relativePath/> <!-- lookup parent from repository -->
  19. </parent>
  20.  
  21. <properties>
  22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  23. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  24. <java.version>1.8</java.version>
  25. <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
  26. <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
  27. <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
  28. </properties>
  29.  
  30. <dependencies>
  31. <dependency>
  32. <groupId>org.thymeleaf.extras</groupId>
  33. <artifactId>thymeleaf-extras-springsecurity4</artifactId>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-starter-security</artifactId>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-starter-web</artifactId>
  46. </dependency>
  47.  
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-test</artifactId>
  51. <scope>test</scope>
  52. </dependency>
  53. </dependencies>
  54.  
  55. <build>
  56. <plugins>
  57. <plugin>
  58. <groupId>org.springframework.boot</groupId>
  59. <artifactId>spring-boot-maven-plugin</artifactId>
  60. </plugin>
  61. </plugins>
  62. </build>
  63.  
  64. </project>

pom.xml

编写配置类:

参考:spring官网Security模块

  1. 1、引入SpringSecurity
  2. 2、编写SpringSecurity的配置类;
  3. @EnableWebSecurity extends WebSecurityConfigurerAdapter
  4. 3、控制请求的访问权限:
  5. configure(HttpSecurity http) {
  6. http.authorizeRequests().antMatchers("/").permitAll()
  7. .antMatchers("/level1/**").hasRole("VIP1")
  8. }
  9. 4、定义认证规则:
  10. configure(AuthenticationManagerBuilder auth){
  11. auth.inMemoryAuthentication()
  12. .withUser("zhangsan").password("123456").roles("VIP1","VIP2")
  13. }
  14. 5、开启自动配置的登陆功能:
  15. configure(HttpSecurity http){
  16. http.formLogin();
  17. }
  18. 6、注销:http.logout();
  19. 7、记住我:Remeberme();

目录

配置类:

  1. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  2. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  3. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  4. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  5.  
  6. @EnableWebSecurity
  7. public class MySecurityConfig extends WebSecurityConfigurerAdapter {
  8.  
  9. @Override
  10. protected void configure(HttpSecurity http) throws Exception {
  11. //super.configure(http);
  12. //定制请求的授权规则
  13. http.authorizeRequests().antMatchers("/").permitAll()
  14. .antMatchers("/level1/**").hasRole("VIP1")
  15. .antMatchers("/level2/**").hasRole("VIP2")
  16. .antMatchers("/level3/**").hasRole("VIP3");
  17.  
  18. //开启自动配置的登陆功能,效果,如果没有登陆,没有权限就会来到登陆页面
  19. http.formLogin().usernameParameter("user").passwordParameter("pwd")
  20. .loginPage("/userlogin");
  21. //1、/login来到登陆页
  22. //2、重定向到/login?error表示登陆失败
  23. //3、更多详细规定
  24. //4、默认post形式的 /login代表处理登陆
  25. //5、一但定制loginPage;那么 loginPage的post请求就是登陆
  26.  
  27. //开启自动配置的注销功能。
  28. http.logout().logoutSuccessUrl("/");//注销成功以后来到首页
  29. //1、访问 /logout 表示用户注销,清空session
  30. //2、注销成功会返回 /login?logout 页面;
  31.  
  32. //开启记住我功能
  33. http.rememberMe().rememberMeParameter("remeber");
  34. //登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录
  35. //点击注销会删除cookie
  36.  
  37. }
  38.  
  39. //定义认证规则
  40. @Override
  41. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  42. //super.configure(auth);
  43. auth.inMemoryAuthentication()
  44. .withUser("zhangsan").password("123456").roles("VIP1","VIP2")
  45. .and()
  46. .withUser("lisi").password("123456").roles("VIP2","VIP3")
  47. .and()
  48. .withUser("wangwu").password("123456").roles("VIP1","VIP3");
  49.  
  50. }
  51. }

MySecurityConfig

视图:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org"
  3. xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <title>Insert title here</title>
  7. </head>
  8. <body>
  9. <h1 align="center">欢迎光临武林秘籍管理系统</h1>
  10. <div sec:authorize="!isAuthenticated()">
  11. <h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
  12. </div>
  13. <div sec:authorize="isAuthenticated()">
  14. <h2><span sec:authentication="name"></span>,您好,您的角色有:
  15. <span sec:authentication="principal.authorities"></span></h2>
  16. <form th:action="@{/logout}" method="post">
  17. <input type="submit" value="注销"/>
  18. </form>
  19. </div>
  20.  
  21. <hr>
  22.  
  23. <div sec:authorize="hasRole('VIP1')">
  24. <h3>普通武功秘籍</h3>
  25. <ul>
  26. <li><a th:href="@{/level1/1}">罗汉拳</a></li>
  27. <li><a th:href="@{/level1/2}">武当长拳</a></li>
  28. <li><a th:href="@{/level1/3}">全真剑法</a></li>
  29. </ul>
  30.  
  31. </div>
  32.  
  33. <div sec:authorize="hasRole('VIP2')">
  34. <h3>高级武功秘籍</h3>
  35. <ul>
  36. <li><a th:href="@{/level2/1}">太极拳</a></li>
  37. <li><a th:href="@{/level2/2}">七伤拳</a></li>
  38. <li><a th:href="@{/level2/3}">梯云纵</a></li>
  39. </ul>
  40.  
  41. </div>
  42.  
  43. <div sec:authorize="hasRole('VIP3')">
  44. <h3>绝世武功秘籍</h3>
  45. <ul>
  46. <li><a th:href="@{/level3/1}">葵花宝典</a></li>
  47. <li><a th:href="@{/level3/2}">龟派气功</a></li>
  48. <li><a th:href="@{/level3/3}">独孤九剑</a></li>
  49. </ul>
  50. </div>
  51.  
  52. </body>
  53. </html>

记住我功能:

出现报错:

原因:模板引擎版本过低

解决方法:更换新版本的thymeleaf

Spring Boot与分布式

分布式:

在分布式系统中,国内常用zookeeper+dubbo组合,而Spring Boot推荐使用全栈的Spring,Spring Boot+Spring Cloud。

分布式系统:

单一应用架构
当网站流量很小时,只需一个应用,将所有功能都部署在一起,以减少部署节点和成本。此时,用于简化增删改查工作量的数据访问框架(ORM)是关键。
垂直应用架构
当访问量逐渐增大,单一应用增加机器带来的加速度越来越小,将应用拆成互不相干的几个应用,以提升效率。此时,用于加速前端页面开发的Web框架(MVC)是关键。
分布式服务架构
当垂直应用越来越多,应用之间交互不可避免,将核心业务抽取出来,作为独立的服务,逐渐形成稳定的服务中心,使前端应用能更快速的响应多变的市场需求。此时,用于提高业务复用及整合的分布式服务框架(RPC)是关键。
流动计算架构
当服务越来越多,容量的评估,小服务资源的浪费等问题逐渐显现,此时需增加一个调度中心基于访问压力实时管理集群容量,提高集群利用率。此时,用于提高机器利用率的资源调度和治理中心(SOA)是关键

Dubbo/Zookeeper

ZooKeeper注册中心
ZooKeeper 是一个分布式的,开放源码的分布式应用程序协调服务。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。
Dubbo分布式服务调用框架
Dubbo是Alibaba开源的分布式服务框架,它最大的特点是按照分层的方式来架构,使用这种方式可以使各个层之间解耦合(或者最大限度地松耦合)。从服务模型的角度来看,Dubbo采用的是一种非常简单的模型,要么是提供方提供服务,要么是消费方消费服务,所以基于这一点可以抽象出服务提供方(Provider)和服务消费方(Consumer)两个角色。

1、安装zookeeper作为注册中心
2、编写服务提供者
3、编写服务消费者
4、整合dubbo

消费:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5.  
  6. <groupId>com.atguigu</groupId>
  7. <artifactId>consumer-user</artifactId>
  8. <version>0.0.1-SNAPSHOT</version>
  9. <packaging>jar</packaging>
  10.  
  11. <name>consumer-user</name>
  12. <description>Demo project for Spring Boot</description>
  13.  
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>1.5.12.RELEASE</version>
  18. <relativePath/> <!-- lookup parent from repository -->
  19. </parent>
  20.  
  21. <properties>
  22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  23. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  24. <java.version>1.8</java.version>
  25. </properties>
  26.  
  27. <dependencies>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-web</artifactId>
  31. </dependency>
  32.  
  33. <dependency>
  34. <groupId>com.alibaba.boot</groupId>
  35. <artifactId>dubbo-spring-boot-starter</artifactId>
  36. <version>0.1.0</version>
  37. </dependency>
  38.  
  39. <!--引入zookeeper的客户端工具-->
  40. <!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
  41. <dependency>
  42. <groupId>com.github.sgroschupf</groupId>
  43. <artifactId>zkclient</artifactId>
  44. <version>0.1</version>
  45. </dependency>
  46.  
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-starter-test</artifactId>
  50. <scope>test</scope>
  51. </dependency>
  52. </dependencies>
  53.  
  54. <build>
  55. <plugins>
  56. <plugin>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-maven-plugin</artifactId>
  59. </plugin>
  60. </plugins>
  61. </build>
  62.  
  63. </project>

pom.xml

  1. dubbo.application.name=consumer-user
  2.  
  3. dubbo.registry.address=zookeeper://118.24.44.169:2181

application.properties

  1. package com.atguigu.user;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. /**
  7. * 1、引入依赖‘
  8. * 2、配置dubbo的注册中心地址
  9. * 3、引用服务
  10. */
  11. @SpringBootApplication
  12. public class ConsumerUserApplication {
  13.  
  14. public static void main(String[] args) {
  15. SpringApplication.run(ConsumerUserApplication.class, args);
  16. }
  17. }

启动类

  1. package com.atguigu.user.service;
  2.  
  3. import com.alibaba.dubbo.config.annotation.Reference;
  4. import com.atguigu.ticket.service.TicketService;
  5. import org.springframework.stereotype.Service;
  6.  
  7. @Service//Spring的service
  8. public class UserService{
  9.  
  10. @Reference//注意两个工程的全类名相同
  11. TicketService ticketService;
  12.  
  13. public void hello(){
  14. String ticket = ticketService.getTicket();
  15. System.out.println("买到票了:"+ticket);
  16. }
  17.  
  18. }

UserService

  1. package com.atguigu.ticket.service;
  2.  
  3. public interface TicketService {
  4.  
  5. public String getTicket();
  6. }

传递接口

  1. package com.atguigu.user;
  2.  
  3. import com.atguigu.user.service.UserService;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9.  
  10. @RunWith(SpringRunner.class)
  11. @SpringBootTest
  12. public class ConsumerUserApplicationTests {
  13.  
  14. @Autowired
  15. UserService userService;
  16.  
  17. @Test
  18. public void contextLoads() {
  19.  
  20. userService.hello();
  21. }
  22.  
  23. }

测试类

服务:

pom文件同上

  1. dubbo.application.name=provider-ticket
  2.  
  3. dubbo.registry.address=zookeeper://118.24.44.169:2181
  4.  
  5. dubbo.scan.base-packages=com.atguigu.ticket.service

application.properties

  1. package com.atguigu.ticket;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. /**
  7. * 1、将服务提供者注册到注册中心
  8. * 1、引入dubbo和zkclient相关依赖
  9. * 2、配置dubbo的扫描包和注册中心地址
  10. * 3、使用@Service发布服务
  11. */
  12. @SpringBootApplication
  13. public class ProviderTicketApplication {
  14.  
  15. public static void main(String[] args) {
  16. SpringApplication.run(ProviderTicketApplication.class, args);
  17. }
  18. }

启动类

  1. package com.atguigu.ticket.service;
  2.  
  3. import com.alibaba.dubbo.config.annotation.Service;
  4. import org.springframework.stereotype.Component;
  5.  
  6. @Component
  7. @Service //将服务发布出去,是dubbo的service
  8. public class TicketServiceImpl implements TicketService {
  9. @Override
  10. public String getTicket() {
  11. return "《厉害了,我的国》";
  12. }
  13. }

TicketServiceImpl

  1. package com.atguigu.ticket.service;
  2.  
  3. public interface TicketService {
  4.  
  5. public String getTicket();
  6. }

TicketService

SpringBoot/Cloud

 Spring Cloud
Spring Cloud是一个分布式的整体解决方案。Spring Cloud 为开发者提供了在分布式系统(配置管理,服务发现,熔断,路由,微代理,控制总线,一次性token,全局琐,leader选举,分布式session,集群状态)中快速构建的工具,使用Spring Cloud的开发者可以快速的启动服务或构建应用、同时能够快速和云平台资源进行对接。

SpringCloud分布式开发五大常用组件
服务发现——Netflix Eureka
客服端负载均衡——Netflix Ribbon
断路器——Netflix Hystrix
服务网关——Netflix Zuul
分布式配置——Spring Cloud Config

Spring Cloud 入门
1、创建provider
2、创建consumer
3、引入Spring Cloud
4、引入Eureka注册中心
5、引入Ribbon进行客户端负载均衡

工程结构:

1.新建空工程:

创建model下载Spring初始化向导

1.创建服务中心:eureka-server    选择服务模块

  1. spring:
  2. application:
  3. name: consumer-user
  4. server:
  5. port: 8200
  6.  
  7. eureka:
  8. instance:
  9. prefer-ip-address: true # 注册服务的时候使用服务的ip地址
  10. client:
  11. service-url:
  12. defaultZone: http://localhost:8761/eureka/

application.yml

启动类:注意要加注解:

  1. package com.atguigu.consumeruser;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  6. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.web.client.RestTemplate;
  9.  
  10. @EnableDiscoveryClient //开启发现服务功能
  11. @SpringBootApplication
  12. public class ConsumerUserApplication {
  13.  
  14. public static void main(String[] args) {
  15. SpringApplication.run(ConsumerUserApplication.class, args);
  16. }
  17.  
  18. @LoadBalanced //使用负载均衡机制
  19. @Bean
  20. public RestTemplate restTemplate(){
  21. return new RestTemplate();
  22. }
  23. }

ConsumerUserApplication

控制层:

  1. package com.atguigu.consumeruser.controller;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import org.springframework.web.client.RestTemplate;
  7.  
  8. @RestController
  9. public class UserController {
  10.  
  11. @Autowired
  12. RestTemplate restTemplate;
  13.  
  14. @GetMapping("/buy")
  15. public String buyTicket(String name){
  16. String s = restTemplate.getForObject("http://PROVIDER-TICKET/ticket", String.class);
  17. return name+"购买了"+s;
  18. }
  19. }

UserController

启动服务:如下即成功

2.新建provider-ticket 的model

  1. server:
  2. port: 8002
  3. spring:
  4. application:
  5. name: provider-ticket
  6.  
  7. eureka:
  8. instance:
  9. prefer-ip-address: true # 注册服务的时候使用服务的ip地址
  10. client:
  11. service-url:
  12. defaultZone: http://localhost:8761/eureka/

application.yml

启动类:

  1. package com.atguigu.providerticket;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. @SpringBootApplication
  7. public class ProviderTicketApplication {
  8.  
  9. public static void main(String[] args) {
  10. SpringApplication.run(ProviderTicketApplication.class, args);
  11. }
  12. }

ProviderTicketApplication

服务层:

  1. package com.atguigu.providerticket.service;
  2.  
  3. import org.springframework.stereotype.Service;
  4.  
  5. @Service
  6. public class TicketService {
  7.  
  8. public String getTicket(){
  9. System.out.println("8002");
  10. return "《厉害了,我的国》";
  11. }
  12. }

TicketService

控制层:

  1. package com.atguigu.providerticket.controller;
  2.  
  3. import com.atguigu.providerticket.service.TicketService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7.  
  8. @RestController
  9. public class TicketController {
  10.  
  11. @Autowired
  12. TicketService ticketService;
  13.  
  14. @GetMapping("/ticket")
  15. public String getTicket(){
  16. return ticketService.getTicket();
  17. }
  18. }

TicketController

3.新建model  consumer-user

  1. spring:
  2. application:
  3. name: consumer-user
  4. server:
  5. port: 8200
  6.  
  7. eureka:
  8. instance:
  9. prefer-ip-address: true # 注册服务的时候使用服务的ip地址
  10. client:
  11. service-url:
  12. defaultZone: http://localhost:8761/eureka/

application.yml

启动类:

  1. package com.atguigu.consumeruser;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  6. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.web.client.RestTemplate;
  9.  
  10. @EnableDiscoveryClient //开启发现服务功能
  11. @SpringBootApplication
  12. public class ConsumerUserApplication {
  13.  
  14. public static void main(String[] args) {
  15. SpringApplication.run(ConsumerUserApplication.class, args);
  16. }
  17.  
  18. @LoadBalanced //使用负载均衡机制
  19. @Bean
  20. public RestTemplate restTemplate(){
  21. return new RestTemplate();
  22. }
  23. }

ConsumerUserApplication

控制层:

  1. package com.atguigu.consumeruser.controller;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import org.springframework.web.client.RestTemplate;
  7.  
  8. @RestController
  9. public class UserController {
  10.  
  11. @Autowired
  12. RestTemplate restTemplate;
  13.  
  14. @GetMapping("/buy")
  15. public String buyTicket(String name){
  16. String s = restTemplate.getForObject("http://PROVIDER-TICKET/ticket", String.class);
  17. return name+"购买了"+s;
  18. }
  19. }

UserController

浏览器测试访问:

成功:

Spring Boot与监控管理

一、监控管理
通过引入spring-boot-starter-actuator,可以使用Spring Boot为我们提供的准生产环境下的应用监控和管理功能。我们可以通过HTTP,JMX,SSH协议来进行操作,自动得到审计、健康及指标信息等

步骤:
引入spring-boot-starter-actuator
通过http方式访问监控端点
可进行shutdown(POST 提交,此端点默认关闭)


关闭即可在浏览器访问查看:

监控和管理端点:

二:定制端点信息:

定制端点一般通过endpoints+端点名+属性名来设置。
修改端点id(endpoints.beans.id=mybeans)
开启远程应用关闭功能(endpoints.shutdown.enabled=true)
关闭端点(endpoints.beans.enabled=false)
开启所需端点
endpoints.enabled=false
endpoints.beans.enabled=true
定制端点访问根路径
management.context-path=/manage
关闭http端点
management.port=-1

三自定义健康指示器:

  1. package com.atguigu.springboot08actuator;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. /**
  7. * 自定义健康状态指示器
  8. * 1、编写一个指示器 实现 HealthIndicator 接口
  9. * 2、指示器的名字 xxxxHealthIndicator
  10. * 3、加入容器中
  11. */
  12. @SpringBootApplication
  13. public class Springboot08ActuatorApplication {
  14.  
  15. public static void main(String[] args) {
  16. SpringApplication.run(Springboot08ActuatorApplication.class, args);
  17. }
  18. }

Springboot08ActuatorApplication

  1. package com.atguigu.springboot08actuator.health;
  2.  
  3. import org.springframework.boot.actuate.health.Health;
  4. import org.springframework.boot.actuate.health.HealthIndicator;
  5. import org.springframework.stereotype.Component;
  6.  
  7. @Component
  8. public class MyAppHealthIndicator implements HealthIndicator {
  9.  
  10. @Override
  11. public Health health() {
  12.  
  13. //自定义的检查方法
  14. //Health.up().build()代表健康
  15. return Health.down().withDetail("msg","服务异常").build();
  16. }
  17. }

MyAppHealthIndicator

Spring Boot与部署

热部署:

在开发中我们修改一个Java文件后想看到效果不得不重启应用,这导致大量时间花费,我们希望不重启应用的情况下,程序可以自动部署(热部署)。有以下四种情况,如何能实现热部署。

1、模板引擎
在Spring Boot中开发情况下禁用模板引擎的cache
页面模板改变ctrl+F9可以重新编译当前页面并生效
2、Spring Loaded
Spring官方提供的热部署程序,实现修改类文件的热部署
下载Spring Loaded(项目地址https://github.com/spring-projects/spring-loaded)
添加运行时参数;
-javaagent:C:/springloaded-1.2.5.RELEASE.jar –noverify
3、JRebel
收费的一个热部署软件
安装插件使用即可
4、Spring Boot Devtools(推荐)
引入依赖

IDEA使用ctrl+F9
或做一些小调整
    Intellij IEDA和Eclipse不同,Eclipse设置了自动编译之后,修改类它会自动编译,而IDEA在非RUN或DEBUG情况下才会自动编译(前提是你已经设置了Auto-Compile)。
设置自动编译(settings-compiler-make project automatically)
ctrl+shift+alt+/(maintenance)
勾选compiler.automake.allow.when.app.running

SpringBoot笔记二:整合篇的更多相关文章

  1. mybatis笔记<二> 整合spring

    mybatis与spring整合需要添加几个jar包,mybatis-spring, spring-context, spring-jdbc 1. spring ioc只要一个jar包就ok 2. 我 ...

  2. springboot笔记08——整合swagger2

    Swagger是什么? Swagger是一个RESTFUL 接口的文档在线自动生成和功能测试的框架.利用swagger2的注解可以快速的在项目中构建Api接口文档,并且提供了测试API的功能. Spr ...

  3. springboot笔记07——整合MyBatis

    前言 Springboot 整合 MyBatis 有两种方式,分别是:"全注解版" 和 "注解.xml混合版". 创建项目 创建Springboot项目,选择依 ...

  4. springboot笔记10——整合Redis

    依赖 <dependencies> <!--web依赖--> <dependency> <groupId>org.springframework.boo ...

  5. Spring Boot 学习笔记(六) 整合 RESTful 参数传递

    Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...

  6. 纯JS实现KeyboardNav(学习笔记)二

    纯JS实现KeyboardNav(学习笔记)二 这篇博客只是自己的学习笔记,供日后复习所用,没有经过精心排版,也没有按逻辑编写 这篇主要是添加css,优化js编写逻辑和代码排版 GitHub项目源码 ...

  7. Springboot security cas整合方案-原理篇

    前言:网络中关于Spring security整合cas的方案有很多例,对于Springboot security整合cas方案则比较少,且有些仿制下来运行也有些错误,所以博主在此篇详细的分析cas原 ...

  8. springboot学习笔记-3 整合redis&mongodb

    一.整合redis 1.1 建立实体类 @Entity @Table(name="user") public class User implements Serializable ...

  9. 源码学习系列之SpringBoot自动配置(篇二)

    源码学习系列之SpringBoot自动配置(篇二)之HttpEncodingAutoConfiguration 源码分析 继上一篇博客源码学习系列之SpringBoot自动配置(篇一)之后,本博客继续 ...

随机推荐

  1. 箭头函数 this指向问题

    1.为什么要用箭头函数 简洁 易用 固定this 指向(箭头函数在this定义时候生效) 2.箭头函数分析this指向 1.this指向调用函数的对象 情况1 var obj={ a:"1& ...

  2. P2023 [AHOI2009]维护序列 区间加乘模板

    题意: 有长为N的数列,不妨设为a1,a2,…,aN .有如下三种操作形式:N<=1e5(1)把数列中的一段数全部乘一个值;(2)把数列中的一段数全部加一个值;(3)询问数列中的一段数的和,由于 ...

  3. js location.href 的用法

    self.location.href="/url" 当前页面打开URL页面: this.location.href="/url" 当前页面打开URL页面: pa ...

  4. 七、linux基础-jdk1.8和weblogic12.2.1.3.0安装

    1.环境探查与准备 安装jdk和weblogic前需要对进行安装的linux系统硬件和软件环境进行探查确认,以确保支持对jdk1.8.0_144_1和weblogic12.2.1.3和的安装.webl ...

  5. hadoop学习笔记(五)hadoop伪分布式集群的搭建

    本文原创,如需转载,请注明作者和原文链接 1.集群搭建的前期准备   见      搭建分布式hadoop环境的前期准备---需要检查的几个点 2.解压tar.gz包 [root@node01 ~]# ...

  6. Java日期时间API系列21-----Jdk8中java.time包中的新的日期时间API类,xk-time时间转换,计算,格式化,解析的工具

    通过工作之余,对Java8中java.time包源码的不断学习,使用和总结,开发了xk-time,初步完成,欢迎试用和提出建议! xk-time xk-time is a datetime conve ...

  7. MyBatis-Spring整合之方式2

    提前叨叨:此方法优化了上一个方式的事务支持,同时简化了一个bean的配置 1.在方式1的基础上修改UserDaoImp文件,改用使用继承SqlSessionDaoSupport的方式.代码如下: pu ...

  8. mac停靠栏动画

    MAC停靠栏 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <ti ...

  9. 开源协议:LGPL协议、OSGi协议

    本文介绍开源的协议. LGPL 是 GNU Lesser General Public License (GNU 宽通用公共许可证)的缩写形式,旧称 GNU Library General Publi ...

  10. template-组件封装

    HTML: //:ligit='ligit' 一致 <div id='app'> <template-swiper :ligit='ligit'></template-s ...