【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博客



相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1天前
|
Java 调度 Spring
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
286 0
|
1天前
|
druid Java 数据库
druid+springboot加解密Druid链接池配置加密密码链接数据库
druid+springboot加解密Druid链接池配置加密密码链接数据库
92 0
|
1天前
|
前端开发 Java 应用服务中间件
Springboot对MVC、tomcat扩展配置
Springboot对MVC、tomcat扩展配置
|
1天前
|
资源调度 JavaScript 前端开发
Vue的路由管理:VueRouter的配置和使用
【4月更文挑战第24天】VueRouter是Vue.js的官方路由管理器,用于在单页面应用中管理URL路径与组件的映射。通过安装并引入VueRouter,设置路由规则和创建router实例,可以实现不同路径下显示不同组件。主要组件包括:`&lt;router-link&gt;`用于创建导航链接,`&lt;router-view&gt;`负责渲染当前路由对应的组件。此外,VueRouter还支持编程式导航和各种高级特性,如嵌套路由、路由参数和守卫,以应对复杂路由场景。
|
1天前
|
安全 Java 开发者
深入理解Spring Boot配置绑定及其实战应用
【4月更文挑战第10天】本文详细探讨了Spring Boot中配置绑定的核心概念,并结合实战示例,展示了如何在项目中有效地使用这些技术来管理和绑定配置属性。
13 1
|
1天前
|
Java 文件存储 Spring
【springboot】logback配置
【springboot】logback配置
20 1
|
1天前
|
Java 微服务 Spring
Spring Boot中获取配置参数的几种方法
Spring Boot中获取配置参数的几种方法
22 2
|
1天前
|
Web App开发 前端开发 Java
SpringBoot配置HTTPS及开发调试
在实际开发过程中,如果后端需要启用https访问,通常项目启动后配置nginx代理再配置https,前端调用时高版本的chrome还会因为证书未信任导致调用失败,通过摸索整理一套开发调试下的https方案,特此分享
21 0
SpringBoot配置HTTPS及开发调试
|
1天前
|
存储 Java 数据库
SpringBoot使用jasypt实现数据库配置加密
这样,你就成功地使用Jasypt实现了Spring Boot中的数据库配置加密,确保敏感信息在配置文件中以加密形式存储,并在应用启动时自动解密。
47 2
|
1天前
|
JavaScript 前端开发
ant design vue 配置菜单外部打开
ant design vue 配置菜单外部打开
17 0