springboot整合redis
中国加油,武汉加油!
篇幅较长,配合右边目录观看
项目准备
- 创建springboot项目nz1904-springboot-09-redis
- 导入Web的springWeb依赖和Lombox依赖和NoSQL的Redis依赖
1. 案例
1.1 定义AppConfig
package com.wpj.config;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootConfiguration
@ComponentScan(basePackages = {"com.wpj"})
public class AppConfig {
}
1.2 定义RedisManager
package com.wpj.manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
/**
* 业务下沉
*/
@Component
public class RedisManager {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 向Redis存放一个键值对
* @param key
* @param value
*/
public void addKeyAndValue(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
/**
*
* @param key
* @return
*/
public String getValueForKey(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
}
1.3 定义Service及其实现类
package com.wpj.service;
public interface IRedisService {
/**
* 添加数据到Redis中
* @param key
* @param value
*/
public void addKeyAndValue(String key, String value);
/**
* 根据键过去值
* @param key
* @return
*/
String getValueForKey(String key);
}
package com.wpj.service.impl;
import com.wpj.manager.RedisManager;
import com.wpj.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RedisServiceImpl implements IRedisService {
@Autowired
private RedisManager redisManager;
@Override
public void addKeyAndValue(String key, String value) {
redisManager.addKeyAndValue(key, value);
}
@Override
public String getValueForKey(String key) {
return redisManager.getValueForKey(key);
}
}
1.4 配置Redis
# 配置Redis
spring.redis.host=47.98.33.215
spring.redis.port=6379
# 最大的连接数
spring.redis.jedis.pool.max-active=10
# 最大最小的空闲连接数
spring.redis.jedis.pool.max-idle= 10
spring.redis.jedis.pool.min-idle=0
# 最大阻塞时间 -1 没有限制
spring.redis.jedis.pool.max-wait=-1
1.5 定义Controller
package com.wpj.controller;
import com.wpj.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RedisController {
@Autowired
private IRedisService iRedisService;
@RequestMapping("/addValue")
public Object addValue(){
iRedisService.addKeyAndValue("springboot-redis","springboot整合Redis");
return "执行完成";
}
@RequestMapping("/getValue")
public String getValue(String key){
return iRedisService.getValueForKey(key);
}
}
1.6 启动主启动类
package com.wpj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}