当前位置: 首页>编程语言>正文

redis部署怎么设置内存linux redis部署到linux

1,首先先从网上下载redis安装包

2,然后使用FileZilla将压缩包上传至linux中

3,再用putty连接linux ,设置window为Change the size of the fort (可以复制粘贴)

设置Connection的时间(这样就算一段时间不使用putty也不会关闭)

4, cd到你安装redis的目录执行解压命令

tar -zxvf redis-4.0.11.tar.gz ,这时会多一个文件,cd进去进行编译,看到

Hint: It.....说明编译成功了

5,接下来要进行安装 PREFIX后面是你指定的安装目录(一般都在usr目录下)

make install PREFIX=/usr/local/redis ,看到下面的♂说明安装完成了,

6,把把/root/redis-4.0.11/redis.conf复制到/usr/local/redis/bin目录下

cp redis.conf /usr/local/redis/bin/

再cd到/usr/local/redis/bin下会看到这样的目录结构

7,接下来就对redis进行配置,vim redis.conf ,将bind注释到,requirepass是设置密码的

daemonize是是否允许远程登陆的

8,开启redis ./redis-server redis.conf, 再输入ps aux|grep redis查看redis的进程到到下图说明成功开启了。

9,关闭操作有两种一种kill -9 还有一种如下图 如何没有设置密码直接./redis-cli

然后shutdown,设置密码的话需要在输入auth 你的密码。(输入quit退出)

到这里redis的安装与配置就已经全部完成了,接下来,就是项目运用了。

项目我分为2个项目,一个是ssm项目,另一个是springboot项目。

1,准备工作,

(1)安装redis客户端RedisDesktopManager(这个在网上有很多,这里就不多说了,有不会的可以私信我)

(2)连接redis

2,编辑applicationContext-redis.xml文件

xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"

xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">

3,添加依赖jedis是redis的组件,jackson是用来处理数据的。

redis.clients

jedis

2.9.0

com.fasterxml.jackson.core

jackson-databind

2.8.3

4,引一个jsonUtil工具类,和一个jedisClient的接口,以及其实现类

package com.sesame.utils;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.JavaType;

import com.fasterxml.jackson.databind.ObjectMapper;

/**

*

*/

public class JsonUtils {

// 定义jackson对象

private static final ObjectMapper MAPPER = new ObjectMapper();

/**

* 将对象转换成json字符串。

*

Title: pojoToJson

*

Description:

* @param data

* @return

*/

public static String objectToJson(Object data) {

try {

String string = MAPPER.writeValueAsString(data);

return string;

} catch (JsonProcessingException e) {

e.printStackTrace();

}

return null;

}

/**

* 将json结果集转化为对象

*

* @param jsonData json数据

* @param clazz 对象中的object类型

* @return

*/

public static T jsonToPojo(String jsonData, Class beanType) {

try {

T t = MAPPER.readValue(jsonData, beanType);

return t;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 将json数据转换成pojo对象list

*

Title: jsonToList

*

Description:

* @param jsonData

* @param beanType

* @return

*/

public static List jsonToList(String jsonData, Class beanType) {

JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);

try {

List list = MAPPER.readValue(jsonData, javaType);

return list;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

package com.sesame.redis;

public interface JedisClient {

String set(String key, String value);

String get(String key);

Boolean exists(String key);

Long expire(String key, int seconds);

Long ttl(String key);

Long incr(String key);

Long hset(String key, String field, String value);

String hget(String key, String field);

Long hdel(String key,String... field);//删除hkey

}

package com.sesame.redis;

import org.springframework.beans.factory.annotation.Autowired;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

public class JedisClientPool implements JedisClient {

@Autowired

private JedisPool jedisPool;

@Override

public String set(String key, String value) {

Jedis jedis = jedisPool.getResource();

String result = jedis.set(key, value);

jedis.close();

return result;

}

@Override

public String get(String key) {

Jedis jedis = jedisPool.getResource();

String result = jedis.get(key);

jedis.close();

return result;

}

@Override

public Boolean exists(String key) {

Jedis jedis = jedisPool.getResource();

Boolean result = jedis.exists(key);

jedis.close();

return result;

}

@Override

public Long expire(String key, int seconds) {

Jedis jedis = jedisPool.getResource();

Long result = jedis.expire(key, seconds);

jedis.close();

return result;

}

@Override

public Long ttl(String key) {

Jedis jedis = jedisPool.getResource();

Long result = jedis.ttl(key);

jedis.close();

return result;

}

@Override

public Long incr(String key) {

Jedis jedis = jedisPool.getResource();

Long result = jedis.incr(key);

jedis.close();

return result;

}

@Override

public Long hset(String key, String field, String value) {

Jedis jedis = jedisPool.getResource();

Long result = jedis.hset(key, field, value);

jedis.close();

return result;

}

@Override

public String hget(String key, String field) {

Jedis jedis = jedisPool.getResource();

String result = jedis.hget(key, field);

jedis.close();

return result;

}

@Override

public Long hdel(String key, String... field) {

Jedis jedis = jedisPool.getResource();

Long hdel = jedis.hdel(key, field);

jedis.close();

return hdel;

}

}

5,接下来就可以编写代码了,定义一个Student的表

CREATE TABLE `student` (

`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' 主键 ',

`name` varchar(50) DEFAULT NULL COMMENT ' 名字 ',

PRIMARY KEY (`id`) USING BTREE

) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='学生表'

6,同样需要在项目中定义一个Student的POJO

package com.sesame.wx.liyuan.bean;

import java.io.Serializable;

public class Student implements Serializable{

private static final long serialVersionUID = 1L;

private Integer id;

private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

7,Dao层

public Student getStudent(Integer stuId);

select id, name from student where id = #{stuId}

8,Service层

public Student getStudent(Integer stuId) {

try {

String jsonstr = client.get("CONTENT_KEY"+stuId);//从redis数据库中获取内容分类下的所有的内容。

//如果存在,说明有缓存

if(StringUtil.isNotEmpty(jsonstr)){

System.out.println("这里有缓存啦!!!!!");

return JsonUtils.jsonToPojo(jsonstr, Student.class); //将json数据转为POJO对象

}

} catch (Exception e1) {

e1.printStackTrace();

}

Student student = liyuanDao.getStudent(stuId);

try {

System.out.println("没有缓存!!!!!!");

client.set("CONTENT_KEY"+stuId, JsonUtils.objectToJson(student)); // 将数据转为json数据传入redis数据库

client.expire("CONTENT_KEY"+stuId, 100); // 设置缓存时间,单位为秒

} catch (Exception e) {

e.printStackTrace();

}

return student;

}

9,Controller层

@RequestMapping("/getStudent")

@ResponseBody

public Map getStudent(Integer stuId) {

Map resMap = new HashMap();

Student student = liyuanSercice.getStudent(stuId);

resMap.put("student", student);

return resMap;

}

当看到下面的图片,说明缓存成功了。TTL是你设置的缓存时间

上面就是ssm使用redis的全部过程了,接下来就介绍springboot项目使用redis,这里还使用了cache插件来整合redis看起来代码更简洁一点。

1,首先创建user表,(我们不在是学生了,变成用户了=-=)

CREATE TABLE `user` (

`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' 主键 ',

`name` varchar(50) DEFAULT NULL COMMENT ' 名字 ',

PRIMARY KEY (`id`) USING BTREE

) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='用户表'

2,配置文件

yml

spring:

redis:

host: 192.168.92.128

port: 6379

password: 123456

cache:

type: redis

cache:

expire-time: 180 // 设置过期时间

CONFIG

package com.walklake.log.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import com.fasterxml.jackson.annotation.PropertyAccessor;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.cache.CacheManager;

import org.springframework.cache.annotation.CachingConfigurerSupport;

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.cache.interceptor.KeyGenerator;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**

* 必须继承CachingConfigurerSupport,不然此类中生成的Bean不会生效(没有替换掉默认生成的,只是一个普通的bean)

* springboot默认生成的缓存管理器和redisTemplate支持的类型很有限,根本不满足我们的需求,会抛出如下异常:

* org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String

*/

@Configuration

@EnableCaching

public class SpringCacheRedisConfig extends CachingConfigurerSupport {

@Value("${cache.expire-time:180}")

private int expireTime;

// 配置key生成器,作用于缓存管理器管理的所有缓存

// 如果缓存注解(@Cacheable、@CacheEvict等)中指定key属性,那么会覆盖此key生成器

@Bean

public KeyGenerator keyGenerator() {

return (target, method, params) -> {

StringBuilder sb = new StringBuilder();

sb.append(target.getClass().getName());

sb.append(method.getName());

for (Object obj : params) {

sb.append(obj.toString());

}

return sb.toString();

};

}

// 缓存管理器管理的缓存都需要有对应的缓存空间,否则抛异常:No cache could be resolved for 'Builder...

@Bean

public CacheManager cacheManager(RedisTemplate redisTemplate) {

RedisCacheManager rcm = new RedisCacheManager(redisTemplate);

rcm.setDefaultExpiration(expireTime); //设置缓存管理器管理的缓存的过期时间, 单位:秒

return rcm;

}

@Bean

public RedisTemplate redisTemplate(RedisConnectionFactory factory) {

StringRedisTemplate template = new StringRedisTemplate(factory);

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

ObjectMapper om = new ObjectMapper();

om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

jackson2JsonRedisSerializer.setObjectMapper(om);

template.setValueSerializer(jackson2JsonRedisSerializer);

template.afterPropertiesSet();

return template;

}

}

3,接下来就是项目了,先在pom文件添加依赖

org.springframework.boot

spring-boot-starter-data-redis

org.springframework.boot

spring-boot-starter-cache

4,创建POJO

package com.walklake.log.entity;

import java.io.Serializable;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

import lombok.Data;

@Data

@Entity

@Table(name="user")

public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private Integer id;

private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

5,Dao层(这里springboot使用的是spring data,非常好用,有时间我写一个spring data的文章)

package com.walklake.log.dao;

import org.springframework.data.repository.CrudRepository;

import com.walklake.log.entity.User;

public interface UserDAO extends CrudRepository {

User findById(Integer id);

}

6,Service(cache插件 @Cacheable为查询,第一次走代码,第二次走redis,@CachePut为更新,每次都会走代码,并将返回值保存到redis数据库中,所以一定要有返回值,

不然会保存null,@CacheEvict为删除,@Caching为组合可以任意搭配前面的注解

package com.walklake.log.service;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.CachePut;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.cache.annotation.Caching;

import org.springframework.stereotype.Service;

import com.walklake.log.dao.UserDAO;

import com.walklake.log.entity.User;

@Service

public class UserService {

public static final String CACHE_KEY = "myCache";

@Autowired

private UserDAO userDAO;

public void saveUser(String name) {

User user = new User();

user.setName(name);

userDAO.save(user);

}

@CacheEvict(value="user",key ="'myCache'+#id")

public void deleteUser(Integer id) {

userDAO.delete(id);

}

@CachePut(value = "user",key ="'myCache'+#user.getId()")

public User updateUser(User user) {

return userDAO.save(user);

}

@Cacheable(value="user",key ="'myCache'+#id")

public User searchUser(Integer id) {

return userDAO.findById(id);

}

@Caching(cacheable = {@Cacheable(value="user",key ="'myCache'+#id")},

put = {@CachePut(value = "user",key ="'myCache'+#user.getId()")},

evict = {@CacheEvict(value="user",key ="'myCache'+#id")}

)

public User updateAndSelect(User user) {

userDAO.delete(user.getId());

return userDAO.save(user);

}

}

7,Controller层

package com.walklake.log.controller;

import java.util.HashMap;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.walklake.log.entity.User;

import com.walklake.log.service.UserService;

/*

* @Author:zjd

* @Date:2019/5/13 15:29

* @Detail:记录签到数据

*/

@RestController

@RequestMapping("/user")

public class UserController {

@Autowired

private UserService userService;

@GetMapping("/save")

@SuppressWarnings("rawtypes")

public Map save(String name) {

Map resMap = new HashMap();

try {

userService.saveUser(name);

resMap.put("result", "保存成功");

} catch (Exception e) {

e.printStackTrace();

resMap.put("result", "保存失败");

}

return resMap;

}

@GetMapping("/delete")

@SuppressWarnings("rawtypes")

public Map delete(Integer id) {

Map resMap = new HashMap();

try {

userService.deleteUser(id);

resMap.put("result", "删除成功");

} catch (Exception e) {

e.printStackTrace();

resMap.put("result", "删除失败");

}

return resMap;

}

@GetMapping("/update")

@SuppressWarnings("rawtypes")

public Map update(Integer id, String name) {

Map resMap = new HashMap();

User user = new User();

user.setId(id);

user.setName(name);

try {

userService.updateUser(user);

resMap.put("result", "更新成功");

} catch (Exception e) {

e.printStackTrace();

resMap.put("result", "更新失败");

}

return resMap;

}

@GetMapping("/search")

@SuppressWarnings("rawtypes")

public Map search(Integer id) {

Map resMap = new HashMap();

try {

User user = userService.searchUser(id);

resMap.put("result", user);

} catch (Exception e) {

e.printStackTrace();

resMap.put("result", "查询失败");

}

return resMap;

}

@GetMapping("/updateAndSelect")

@SuppressWarnings("rawtypes")

public Map updateAndSelect(Integer id, String name) {

Map resMap = new HashMap();

User user = new User();

user.setId(id);

user.setName(name);

try {

userService.updateUser(user);

resMap.put("result", "更新成功");

} catch (Exception e) {

e.printStackTrace();

resMap.put("result", "更新失败");

}

return resMap;

}

}

8,接下来就进行测试了

(1)首先测试查询,看到下面的图片说明成功了

(2)然后测试更新,看到下面的图片说明成功了

(3)测试删除,看到下面的图片说明成功了

(4)最后测试组合组件,看到下面的图片说明成功了

全部搞定!!!


https://www.xamrdz.com/lan/59q1923833.html

相关文章: