springboot之redis
1、pom.xml文件添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.4.3.RELEASE</version> </dependency>
2、yml文件添加redis
#默认使用配置 spring: profiles: active: @activatedProperties@ redis: host: 127.0.0.1 port: 6379 password: lettuce: pool: max-active: 100 max-idle: 10 max-wait: 100000
3、添加配置文件RedisConfig.java
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import redis.clients.jedis.JedisPoolConfig; @Configuration @EnableAutoConfiguration public class RedisConfig { @Bean @ConfigurationProperties(prefix = "spring.redis.pool") public JedisPoolConfig getRedisConfig(){ JedisPoolConfig config = new JedisPoolConfig(); return config; } @Bean @ConfigurationProperties(prefix = "spring.redis") public JedisConnectionFactory getConnectionFactory() { JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setUsePool(true); JedisPoolConfig config = getRedisConfig(); factory.setPoolConfig(config); return factory; } @Bean public RedisTemplate<?, ?> getRedisTemplate() { JedisConnectionFactory factory = getConnectionFactory(); factory.setDatabase(2); #设置保存数据的库 RedisTemplate<?, ?> template = new StringRedisTemplate(factory); return template; } }
4、controller层实现
@Autowired StringRedisTemplate redisTemplate; @RequestMapping("/showUser") @ResponseBody public User toIndex(HttpServletRequest request, Model model){ int userId = Integer.parseInt(request.getParameter("id")); User user = this.userService.getUserById(userId); redisTemplate.opsForValue().set("user",user.toString()); return user; }
完毕!
本文来自博客园,作者:小白啊小白,Fighting,转载请注明原文链接:https://www.cnblogs.com/ywjfx/p/11389134.html