【SpringBoot+Vue】SpringBoot配置Vue

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: 【SpringBoot+Vue】SpringBoot配置Vue

1:添加pom依赖

1. <!-- Spring Boot Redis依赖 -->
2. <!-- 注意:1.5版本的依赖和2.0的依赖不一样,注意看哦 1.5我记得名字里面应该没有“data”, 2.0必须是“spring-boot-starter-data-redis” 这个才行 -->
3. <dependency>
4. <groupId>org.springframework.boot</groupId>
5. <artifactId>spring-boot-starter-data-redis</artifactId>
6. <!-- 1.5的版本默认采用的连接池技术是jedis 2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar -->
7. <exclusions>
8. <exclusion>
9. <groupId>redis.clients</groupId>
10. <artifactId>jedis</artifactId>
11. </exclusion>
12. <exclusion>
13. <groupId>io.lettuce</groupId>
14. <artifactId>lettuce-core</artifactId>
15. </exclusion>
16. </exclusions>
17. </dependency>
18. 
19. <!-- 添加jedis客户端 -->
20. <dependency>
21. <groupId>redis.clients</groupId>
22. <artifactId>jedis</artifactId>
23. </dependency>
24. 
25. <!--spring2.0集成redis所需common-pool2 -->
26. <!-- 必须加上,jedis依赖此 -->
27. <!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/ -->
28. <dependency>
29. <groupId>org.apache.commons</groupId>
30. <artifactId>commons-pool2</artifactId>
31. </dependency>

注意,如果其中的<dependency></dependency>报错,那么就在前面和后面加上</dependencies>如图

 

2:配置application.properties文件

1. #redis
2. spring.jpa.database=0
3. spring.redis.host=127.0.0.1
4. spring.redis.password=
5. spring.redis.port=6379
6. # 数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
7. spring.redis.timeout=10000
8. 
9. # 连接池配置,2.0中直接使用jedis或者lettuce配置连接池
10. # 最大活跃连接数,负数为不限制
11. spring.redis.jedis.pool.max-active=8
12. # 等待可用连接的最大时间,负数为不限制
13. spring.redis.jedis.pool.max-wait=-1
14. # 最大空闲连接数
15. spring.redis.jedis.pool.max-idle=8
16. # 最小空闲连接数
17. spring.redis.jedis.pool.min-idle=0

3:RedisConfiguration配置文件

1. package com.sjx.config;
2. 
3. import com.fasterxml.jackson.annotation.JsonAutoDetect;
4. import com.fasterxml.jackson.annotation.PropertyAccessor;
5. import com.fasterxml.jackson.databind.ObjectMapper;
6. import org.slf4j.Logger;
7. import org.slf4j.LoggerFactory;
8. import org.springframework.beans.factory.annotation.Autowired;
9. import org.springframework.beans.factory.annotation.Value;
10. import org.springframework.boot.context.properties.ConfigurationProperties;
11. import org.springframework.cache.Cache;
12. import org.springframework.cache.CacheManager;
13. import org.springframework.cache.annotation.CachingConfigurerSupport;
14. import org.springframework.cache.annotation.EnableCaching;
15. import org.springframework.cache.interceptor.CacheErrorHandler;
16. import org.springframework.cache.interceptor.KeyGenerator;
17. import org.springframework.context.annotation.Bean;
18. import org.springframework.context.annotation.Configuration;
19. import org.springframework.data.redis.cache.RedisCacheManager;
20. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
21. import org.springframework.data.redis.core.RedisTemplate;
22. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
23. import org.springframework.data.redis.serializer.RedisSerializer;
24. import org.springframework.data.redis.serializer.StringRedisSerializer;
25. import redis.clients.jedis.JedisPool;
26. import redis.clients.jedis.JedisPoolConfig;
27. 
28. /**
29.  * @ClassName: RedisConfiguration
30.  * @Description:TODO(这里用一句话描述这个类的作用)
31.  * @author: 沈均晓
32.  * @date: 2018年9月19日 上午11:18:33
33.  */
34. @Configuration
35. // 必须加,使配置生效
36. @EnableCaching
37. public class RedisConfiguration extends CachingConfigurerSupport {
38. 
39.   /**
40.    * Logger
41.    */
42.   private static final Logger logger = LoggerFactory.getLogger(RedisConfiguration.class);
43. 
44.   @Autowired
45.   private JedisConnectionFactory jedisConnectionFactory;
46. 
47.   @Bean
48.   public KeyGenerator keyGenerator() {
49.     // 设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存
50.     // 使用:进行分割,可以很多显示出层级关系
51.     // 这里其实就是new了一个KeyGenerator对象,只是这是lambda表达式的写法,我感觉很好用,大家感兴趣可以去了解下
52.     return (target, method, params) -> {
53.       StringBuilder sb = new StringBuilder();
54.       sb.append(target.getClass().getName());
55.       sb.append(":");
56.       sb.append(method.getName());
57.       for (Object obj : params) {
58.         sb.append(":" + String.valueOf(obj));
59.       }
60.       String rsToUse = String.valueOf(sb);
61.       logger.info("自动生成Redis Key -> [{}]", rsToUse);
62.       return rsToUse;
63.     };
64.   }
65. 
66.   @Bean
67.   public CacheManager cacheManager() {
68.     // 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置
69.     logger.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
70.     RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
71.         .fromConnectionFactory(jedisConnectionFactory);
72.     return builder.build();
73.   }
74. 
75.   @Bean
76.   public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
77.     // 设置序列化
78.     Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
79.     ObjectMapper om = new ObjectMapper();
80.     om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
81.     om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
82.     jackson2JsonRedisSerializer.setObjectMapper(om);
83.     // 配置redisTemplate
84.     RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
85.     redisTemplate.setConnectionFactory(jedisConnectionFactory);
86.     RedisSerializer stringSerializer = new StringRedisSerializer();
87.     redisTemplate.setKeySerializer(stringSerializer); // key序列化
88.     redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化
89.     redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
90.     redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化
91.     redisTemplate.afterPropertiesSet();
92.     return redisTemplate;
93.   }
94. 
95.   @Override
96.   @Bean
97.   public CacheErrorHandler errorHandler() {
98.     // 异常处理,当Redis发生异常时,打印日志,但是程序正常走
99.     logger.info("初始化 -> [{}]", "Redis CacheErrorHandler");
100.    CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
101.      @Override
102.      public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
103.        logger.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
104.      }
105. 
106.      @Override
107.      public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
108.        logger.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
109.      }
110. 
111.      @Override
112.      public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
113.        logger.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
114.      }
115. 
116.      @Override
117.      public void handleCacheClearError(RuntimeException e, Cache cache) {
118.        logger.error("Redis occur handleCacheClearError:", e);
119.      }
120.    };
121.    return cacheErrorHandler;
122.  }
123. 
124.  /**
125.   * 此内部类就是把yml的配置数据,进行读取,创建JedisConnectionFactory和JedisPool,以供外部类初始化缓存管理器使用
126.   * 不了解的同学可以去看@ConfigurationProperties和@Value的作用
127.   *
128.   */
129.  @ConfigurationProperties
130.  class DataJedisProperties {
131.    @Value("${spring.redis.host}")
132.    private String host;
133.    @Value("${spring.redis.password}")
134.    private String password;
135.    @Value("${spring.redis.port}")
136.    private int port;
137.    @Value("${spring.redis.timeout}")
138.    private int timeout;
139.    @Value("${spring.redis.jedis.pool.max-idle}")
140.    private int maxIdle;
141.    @Value("${spring.redis.jedis.pool.max-wait}")
142.    private long maxWaitMillis;
143. 
144.    @Bean
145.    JedisConnectionFactory jedisConnectionFactory() {
146.      logger.info("Create JedisConnectionFactory successful");
147.      JedisConnectionFactory factory = new JedisConnectionFactory();
148.      factory.setHostName(host);
149.      factory.setPort(port);
150.      factory.setTimeout(timeout);
151.      factory.setPassword(password);
152.      return factory;
153.    }
154. 
155.    @Bean
156.    public JedisPool redisPoolFactory() {
157.      logger.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);
158.      JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
159.      jedisPoolConfig.setMaxIdle(maxIdle);
160.      jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
161. 
162.      JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
163.      return jedisPool;
164.    }
165.  }
166. 
167. }

4、在实现类中使用

1. package com.sjx.service.impl;
2. 
3. import java.util.List;
4. 
5. import javax.annotation.Resource;
6. 
7. import org.springframework.beans.factory.annotation.Autowired;
8. import org.springframework.cache.annotation.Cacheable;
9. import org.springframework.data.redis.core.StringRedisTemplate;
10. import org.springframework.stereotype.Service;
11. 
12. import com.alibaba.fastjson.JSON;
13. import com.sjx.dao.AttachmentDao;
14. import com.sjx.entity.Attachment;
15. import com.sjx.service.AttachmentService;
16. import com.sjx.util.ResultMap;
17. 
18. @Service
19. public class AttachmentServiceImpl implements AttachmentService {
20. 
21.   @Resource
22.   private AttachmentDao attachmentdao;
23. 
24.   @Autowired
25.   StringRedisTemplate stringRedisTemplate;
26. 
27.   @Override
28.   public ResultMap insertSelective(Attachment attachment) {
29.     // TODO Auto-generated method stub
30.     int insert = attachmentdao.insert(attachment);
31.     if (insert < 0) {
32.       return ResultMap.error("添加失败");
33.     }
34.     return ResultMap.ok("添加成功");
35.   }
36. 
37.   @Override
38.   public ResultMap deleteByPrimaryKey(Long id) {
39.     // TODO Auto-generated method stub
40.     int deleteByPrimaryKey = attachmentdao.deleteByPrimaryKey(id);
41.     if (deleteByPrimaryKey < 0) {
42.       return ResultMap.error("删除失败");
43.     }
44.     return ResultMap.ok("删除成功");
45.   }
46. 
47.   @Override
48.   public ResultMap selectByPrimaryKey(Long id) {
49.     Attachment selectByPrimaryKey = attachmentdao.selectByPrimaryKey(id);
50.     stringRedisTemplate.opsForValue().append("attachment",JSON.toJSONString(selectByPrimaryKey));
51.     ResultMap resultMap = new ResultMap();
52.     resultMap.put("Attachment", selectByPrimaryKey);
53.     return resultMap;
54.   }
55. 
56.   @Override
57.   public ResultMap SelectiveSelectByAttachment(Attachment attachment) {
58.     List<Attachment> selectiveSelectByAttachment = attachmentdao.SelectiveSelectByAttachment(attachment);
59.     stringRedisTemplate.opsForList().leftPush("attachmentList", JSON.toJSONString(selectiveSelectByAttachment));
60.     ResultMap resultMap = new ResultMap();
61.     resultMap.put("Attachment", selectiveSelectByAttachment);
62.     return resultMap;
63.   }
64. 
65.   @Override
66.   public ResultMap updateByPrimaryKeySelective(Attachment attachment) {
67.     int updateByPrimaryKeySelective = attachmentdao.updateByPrimaryKeySelective(attachment);
68.     if (updateByPrimaryKeySelective < 0) {
69.       return ResultMap.error("更新失败");
70.     }
71.     return ResultMap.ok("更新成功");
72.   }
73. 
74. }

此篇文章借鉴CSDN博主:Shen_Junxiao

具体操作可以去他的文章查看,谢谢。(19条消息) SpringBoot使用redis详尽教程_springboot 默认关闭redis_Shen_Junxiao的博客-CSDN博客



相关文章
|
5月前
|
Java Spring
Spring Boot配置的优先级?
在Spring Boot项目中,配置可通过配置文件和外部配置实现。支持的配置文件包括application.properties、application.yml和application.yaml,优先级依次降低。外部配置常用方式有Java系统属性(如-Dserver.port=9001)和命令行参数(如--server.port=10010),其中命令行参数优先级高于系统属性。整体优先级顺序为:命令行参数 &gt; Java系统属性 &gt; application.properties &gt; application.yml &gt; application.yaml。
980 0
|
2月前
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
310 3
|
3月前
|
前端开发 安全 Java
基于springboot+vue开发的会议预约管理系统
一个完整的会议预约管理系统,包含前端用户界面、管理后台和后端API服务。 ### 后端 - **框架**: Spring Boot 2.7.18 - **数据库**: MySQL 5.6+ - **ORM**: MyBatis Plus 3.5.3.1 - **安全**: Spring Security + JWT - **Java版本**: Java 11 ### 前端 - **框架**: Vue 3.3.4 - **UI组件**: Element Plus 2.3.8 - **构建工具**: Vite 4.4.5 - **状态管理**: Pinia 2.1.6 - **HTTP客户端
367 4
基于springboot+vue开发的会议预约管理系统
|
8月前
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
521 7
|
3月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
565 5
|
4月前
|
前端开发 JavaScript Java
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
本系统基于SpringBoot与Vue3开发,实现校园食堂评价功能。前台支持用户注册登录、食堂浏览、菜品查看及评价发布;后台提供食堂、菜品与评价管理模块,支持权限控制与数据维护。技术栈涵盖SpringBoot、MyBatisPlus、Vue3、ElementUI等,适配响应式布局,提供完整源码与数据库脚本,可直接运行部署。
244 6
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
|
3月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
187 0
探索Spring Boot的@Conditional注解的上下文配置
|
9月前
|
缓存 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
1031 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
|
4月前
|
安全 算法 Java
在Spring Boot中应用Jasypt以加密配置信息。
通过以上步骤,可以在Spring Boot应用中有效地利用Jasypt对配置信息进行加密,这样即使配置文件被泄露,其中的敏感信息也不会直接暴露给攻击者。这是一种在不牺牲操作复杂度的情况下提升应用安全性的简便方法。
1008 10
|
9月前
|
Java 关系型数据库 数据库
微服务——SpringBoot使用归纳——Spring Boot事务配置管理——Spring Boot 事务配置
本文介绍了 Spring Boot 中的事务配置与使用方法。首先需要导入 MySQL 依赖,Spring Boot 会自动注入 `DataSourceTransactionManager`,无需额外配置即可通过 `@Transactional` 注解实现事务管理。接着通过创建一个用户插入功能的示例,展示了如何在 Service 层手动抛出异常以测试事务回滚机制。测试结果表明,数据库中未新增记录,证明事务已成功回滚。此过程简单高效,适合日常开发需求。
1153 0