java spring boot 部署redis
java spring boot 部署redis
1 先下载依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>2 弄下配置环境
#编码格式 spring.http.encoding.force=true spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true server.tomcat.uri-encoding=UTF-8 #redis配置 #Redis服务器地址 spring.redis.host=127.0.0.1 #Redis服务器连接端口 spring.redis.port=6379 #Redis数据库索引(默认为0) spring.redis.database=0 #连接池最大连接数(使用负值表示没有限制) spring.redis.jedis.pool.max-active=50 #连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.jedis.pool.max-wait=3000 #连接池中的最大空闲连接 spring.redis.jedis.pool.max-idle=20 #连接池中的最小空闲连接 spring.redis.jedis.pool.min-idle=2 #连接超时时间(毫秒) spring.redis.timeout=5000
3 弄个redis封装类
package com.example.demo2122;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* redis操作工具类.</br>
* (基于RedisTemplate)
* @author xcbeyond
* 2018年7月19日下午2:56:24
*/
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 读取缓存
*
* @param key
* @return
*/
public String get(final String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 写入缓存
*/
public boolean set(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 更新缓存
*/
public boolean getAndSet(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().getAndSet(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 删除缓存
*/
public boolean delete(final String key) {
boolean result = false;
try {
redisTemplate.delete(key);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}4 测试
package com.example.demo2122;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.*;
@RestController
public class HelloControl {
@Resource
private RedisUtils redisUtils;
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
redisUtils.set("redis_key", "redis_vale");
String value = redisUtils.get("redis_key");
return value;
}
}