新建springboot项目
pom文件添加redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis配置文件
spring:
redis:
host: 127.0.0.1
port: 16376
jedis:
pool:
min-idle: 0
max-idle: 8
max-active: 80
max-wait: 1000
redis配置类
package com.redis.springboot.demo.redisspringbootdemo.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
测试接口
package com.redis.springboot.demo.redisspringbootdemo.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/redis/save")
public String put(@RequestParam String key, @RequestParam String value) {
redisTemplate.opsForValue().set(key, value);
return "ok";
}
@GetMapping("/redis/get")
public String gett(@RequestParam String key) {
String result = (String) redisTemplate.opsForValue().get(key);
return result;
}
}
通过redis-cli查看
127.0.0.1:16379> get name
"jack"
127.0.0.1:16379>